wiki.techinc.nl/includes/ResourceLoader/FileModule.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1522 lines
49 KiB
PHP
Raw Normal View History

<?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
*/
namespace MediaWiki\ResourceLoader;
use CSSJanus;
use Exception;
use FileContentsHasher;
use InvalidArgumentException;
use LogicException;
use MediaWiki\Languages\LanguageFallback;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Output\OutputPage;
use MediaWiki\Registration\ExtensionRegistry;
use RuntimeException;
use Wikimedia\Minify\CSSMin;
use Wikimedia\RequestTimeout\TimeoutException;
/**
* Module based on local JavaScript/CSS files.
*
* The following public methods can query the database:
*
* - getDefinitionSummary / / Module::getFileDependencies.
* - getVersionHash / getDefinitionSummary / / Module::getFileDependencies.
* - getStyles / Module::saveFileDependencies.
*
* @ingroup ResourceLoader
* @see $wgResourceModules
* @since 1.17
*/
class FileModule extends Module {
/** @var string Local base path, see __construct() */
protected $localBasePath = '';
/** @var string Remote base path, see __construct() */
protected $remoteBasePath = '';
/**
* @var array<int,string|FilePath> List of JavaScript file paths to always include
*/
protected $scripts = [];
/**
* @var array<string,array<int,string|FilePath>> Lists of JavaScript files by language code
*/
protected $languageScripts = [];
/**
* @var array<string,array<int,string|FilePath>> Lists of JavaScript files by skin name
*/
protected $skinScripts = [];
/**
* @var array<int,string|FilePath> List of paths to JavaScript files to include in debug mode
*/
protected $debugScripts = [];
/**
* @var array<int,string|FilePath> List of CSS file files to always include
*/
protected $styles = [];
/**
* @var array<string,array<int,string|FilePath>> Lists of CSS files by skin name
*/
protected $skinStyles = [];
/**
* Packaged files definition, to bundle and make available client-side via `require()`.
*
* @see FileModule::expandPackageFiles()
* @var null|array
* @phan-var null|array<int,string|FilePath|array{main?:bool,name?:string,file?:string|FilePath,type?:string,content?:mixed,config?:array,callback?:callable,callbackParam?:mixed,versionCallback?:callable}>
*/
protected $packageFiles = null;
/**
* @var array Expanded versions of $packageFiles, lazy-computed by expandPackageFiles();
* keyed by context hash
*/
private $expandedPackageFiles = [];
/**
* @var array Further expanded versions of $expandedPackageFiles, lazy-computed by
* getPackageFiles(); keyed by context hash
*/
private $fullyExpandedPackageFiles = [];
/**
* @var string[] List of modules this module depends on
*/
protected $dependencies = [];
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
/**
* @var null|string File name containing the body of the skip function
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
*/
protected $skipFunction = null;
/**
* @var string[] List of message keys used by this module
*/
protected $messages = [];
/** @var array<int|string,string|FilePath> List of the named templates used by this module */
protected $templates = [];
/** @var null|string Name of group to load this module in */
protected $group = null;
/** @var bool Link to raw files in debug mode */
protected $debugRaw = true;
/** @var bool Whether CSSJanus flipping should be skipped for this module */
protected $noflip = false;
/** @var bool Whether to skip the structure test ResourcesTest::testRespond() */
protected $skipStructureTest = false;
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
/**
* @var bool Whether getStyleURLsForDebug should return raw file paths,
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
* or return load.php urls
*/
protected $hasGeneratedStyles = false;
/**
* @var string[] Place where readStyleFile() tracks file dependencies
*/
protected $localFileRefs = [];
/**
* @var string[] Place where readStyleFile() tracks file dependencies for non-existent files.
* Used in tests to detect missing dependencies.
*/
protected $missingLocalFileRefs = [];
/**
* @var VueComponentParser|null Lazy-created by getVueComponentParser()
*/
protected $vueComponentParser = null;
/**
* Construct a new module from an options array.
*
* @param array $options See $wgResourceModules for the available options.
* @param string|null $localBasePath Base path to prepend to all local paths in $options.
* Defaults to MW_INSTALL_PATH
* @param string|null $remoteBasePath Base path to prepend to all remote paths in $options.
* Defaults to $wgResourceBasePath
*/
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
public function __construct(
array $options = [],
?string $localBasePath = null,
?string $remoteBasePath = null
) {
// Flag to decide whether to automagically add the mediawiki.template module
$hasTemplates = false;
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
// localBasePath and remoteBasePath both have unbelievably long fallback chains
// and need to be handled separately.
[ $this->localBasePath, $this->remoteBasePath ] =
self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
// Extract, validate and normalise remaining options
foreach ( $options as $member => $option ) {
switch ( $member ) {
// Lists of file paths
case 'scripts':
case 'debugScripts':
case 'styles':
case 'packageFiles':
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
$this->{$member} = is_array( $option ) ? $option : [ $option ];
break;
case 'templates':
$hasTemplates = true;
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
$this->{$member} = is_array( $option ) ? $option : [ $option ];
break;
// Collated lists of file paths
case 'languageScripts':
case 'skinScripts':
case 'skinStyles':
if ( !is_array( $option ) ) {
throw new InvalidArgumentException(
"Invalid collated file path list error. " .
"'$option' given, array expected."
);
}
foreach ( $option as $key => $value ) {
if ( !is_string( $key ) ) {
throw new InvalidArgumentException(
"Invalid collated file path list key error. " .
"'$key' given, string expected."
);
}
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
$this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
}
break;
case 'deprecated':
$this->deprecated = $option;
break;
// Lists of strings
case 'dependencies':
case 'messages':
// Normalise
$option = array_values( array_unique( (array)$option ) );
sort( $option );
$this->{$member} = $option;
break;
// Single strings
case 'group':
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
case 'skipFunction':
$this->{$member} = (string)$option;
break;
// Single booleans
case 'debugRaw':
case 'noflip':
case 'skipStructureTest':
$this->{$member} = (bool)$option;
break;
}
}
if ( isset( $options['scripts'] ) && isset( $options['packageFiles'] ) ) {
throw new InvalidArgumentException( "A module may not set both 'scripts' and 'packageFiles'" );
}
if ( isset( $options['packageFiles'] ) && isset( $options['skinScripts'] ) ) {
throw new InvalidArgumentException( "Options 'skinScripts' and 'packageFiles' cannot be used together." );
}
if ( $hasTemplates ) {
$this->dependencies[] = 'mediawiki.template';
// Ensure relevant template compiler module gets loaded
foreach ( $this->templates as $alias => $templatePath ) {
if ( is_int( $alias ) ) {
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
$alias = $this->getPath( $templatePath );
}
$suffix = explode( '.', $alias );
$suffix = end( $suffix );
$compilerModule = 'mediawiki.template.' . $suffix;
if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
$this->dependencies[] = $compilerModule;
}
}
}
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
}
/**
* Extract a pair of local and remote base paths from module definition information.
* Implementation note: the amount of global state used in this function is staggering.
*
* @param array $options Module definition
* @param string|null $localBasePath Path to use if not provided in module definition. Defaults
* to MW_INSTALL_PATH
* @param string|null $remoteBasePath Path to use if not provided in module definition. Defaults
* to $wgResourceBasePath
* @return string[] [ localBasePath, remoteBasePath ]
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
*/
public static function extractBasePaths(
array $options = [],
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
$localBasePath = null,
$remoteBasePath = null
) {
// The different ways these checks are done, and their ordering, look very silly,
// but were preserved for backwards-compatibility just in case. Tread lightly.
$remoteBasePath ??= MediaWikiServices::getInstance()->getMainConfig()
->get( MainConfigNames::ResourceBasePath );
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
if ( isset( $options['remoteExtPath'] ) ) {
$extensionAssetsPath = MediaWikiServices::getInstance()->getMainConfig()
->get( MainConfigNames::ExtensionAssetsPath );
$remoteBasePath = $extensionAssetsPath . '/' . $options['remoteExtPath'];
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
}
if ( isset( $options['remoteSkinPath'] ) ) {
$stylePath = MediaWikiServices::getInstance()->getMainConfig()
->get( MainConfigNames::StylePath );
$remoteBasePath = $stylePath . '/' . $options['remoteSkinPath'];
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
}
if ( array_key_exists( 'localBasePath', $options ) ) {
$localBasePath = (string)$options['localBasePath'];
}
if ( array_key_exists( 'remoteBasePath', $options ) ) {
$remoteBasePath = (string)$options['remoteBasePath'];
}
resourceloader: Remove wfExpandUrl() coupling from CSSMin There are three cases in CSSMin::remap where performs path resolution. 1. Absolute local path URLs to full URL. Example: url(/static/foo.png), url(/w/index.php?…), etc. These previously used wfExpandUrl(), which got the server name and protocol directly from $wgServer. We will now use the $remote parameter to get this information instead, which is generally set to something like https://wiki/w/resources/foo, and thus naturally contains the server name and protocol. The resolution is powered by the Net_URL2 library, allowing this to work outside Mediawiki as well. Some tests needed to change because they were calling CSSMin::remap with an incomplete $remote dummy values like "/" or "/w, because the test author (past me) was trying to be clever by not supplying it, knowing MW would ignore it. Now that it is consistently used, like normal calls from ResourceLoader would, the expected values will always be based on http://localhost/w, instead of sometimes the competing $wgServer value of `https://expand.example`. 2. Relative local path to full URL Example: url(foo.png), url(../foo.png), url(bar/foo.png) These were already using $remote. The only change is that they now use Net_URL2 library instead of blind string concatenation. One of the benefits of this is that we will no longer need to call wfRemoveDotSegments() to get rid of things like double slashes or redundant "../" sequences. Previously, thing like "foo//bar" or "foo/../bar" were cleaned up only due to wfRemoveDotSegments(). This is now naturally handled by Net_URL2. 3. Remote URLs Example: url(http://example.org/bar.png), url(//example.org/bar.png) This is generally not used in source code, but gadgets may use this, e.g. for upload.wikimedia.org or cross-wiki imports. Other changes: * One test case used spaces within the URL string in CSS, which the net_url2 library represents with percent-encoding instead. Same thing either way. Bug: T88914 Change-Id: Ibef70cc934c0ee8260a244c51bca9fb88c1c0d88
2020-09-11 21:35:37 +00:00
if ( $remoteBasePath === '' ) {
// If MediaWiki is installed at the document root (not recommended),
// then wgScriptPath is set to the empty string by the installer to
// ensure safe concatenating of file paths (avoid "/" + "/foo" being "//foo").
// However, this also means the path itself can be an invalid URI path,
// as those must start with a slash. Within ResourceLoader, we will not
// do such primitive/unsafe slash concatenation and use URI resolution
// instead, so beyond this point, to avoid fatal errors in CSSMin::resolveUrl(),
// do a best-effort support for docroot installs by casting this to a slash.
$remoteBasePath = '/';
}
return [ $localBasePath ?? MW_INSTALL_PATH, $remoteBasePath ];
}
public function getScript( Context $context ) {
$packageFiles = $this->getPackageFiles( $context );
if ( $packageFiles !== null ) {
foreach ( $packageFiles['files'] as &$file ) {
if ( $file['type'] === 'script+style' ) {
$file['content'] = $file['content']['script'];
$file['type'] = 'script';
}
}
return $packageFiles;
}
$files = $this->getScriptFiles( $context );
foreach ( $files as &$file ) {
$this->readFileInfo( $context, $file );
}
return [ 'plainScripts' => $files ];
}
/**
* @param Context $context
* @return string[] URLs
*/
public function getScriptURLsForDebug( Context $context ) {
resourceloader: Fix debug mode for RL-to-RL cross-wiki module loads The native "foreign module source" feature, as used by the GlobalCssJs extension, did not work correctly in debug mode as the urls returned by the remote wiki were formatted as "/w/load.php...", which would be interpreted by the browser relative to the host document, instead of relative to the parent script. For example: 1. Page view on en.wikipedia.org. 2. Script call to meta.wikimedia.org/w/load.php?debug=true&modules=ext.globalCssJs.user&user This URL is formatted by getScriptURLsForDebug on en.wikipedia.org, when building the article HTML. It knows the modules is on Meta, and formats it as such. So far so good. 3. meta.wikimedia.org responds with an array of urls for sub resources. That array contained URLs like "/w/load.php...only=scripts". These were formatted by getScriptURLsForDebug running on Meta, no longer with a reason to make it a Meta-Wiki URL as it isn't perceived as cross-wiki. It is indistinguishable from debugging a Meta-Wiki page view from its perspective. This patch affects scenario 3 by always expanding it relative to the current-request's wgServer. We still only do this in debug mode. There is not yet a need to do this in non-debug mode, and if there was we'd likely want to find a way to avoid it in the common case to keep embedded URLs short. The ResourceLoader::expandUrl() method is similar to the one in Wikimedia\Minify\CSSMin. Test Plan: * view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=site For Module base class. Before, the array entries were relative. After, they are full. * view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=jquery For FileModule. Before, the array entries were relative. After, they are full. * view-source:http://mw.localhost:8080/wiki/Main_Page?debug=true Unchanged. * view-source:http://mw.localhost:8080/wiki/Main_Page Unchanged. Bug: T255367 Change-Id: I83919744b2677c7fb52b84089ecc60b89957d32a
2021-08-25 02:36:25 +00:00
$rl = $context->getResourceLoader();
$config = $this->getConfig();
$server = $config->get( MainConfigNames::Server );
resourceloader: Fix debug mode for RL-to-RL cross-wiki module loads The native "foreign module source" feature, as used by the GlobalCssJs extension, did not work correctly in debug mode as the urls returned by the remote wiki were formatted as "/w/load.php...", which would be interpreted by the browser relative to the host document, instead of relative to the parent script. For example: 1. Page view on en.wikipedia.org. 2. Script call to meta.wikimedia.org/w/load.php?debug=true&modules=ext.globalCssJs.user&user This URL is formatted by getScriptURLsForDebug on en.wikipedia.org, when building the article HTML. It knows the modules is on Meta, and formats it as such. So far so good. 3. meta.wikimedia.org responds with an array of urls for sub resources. That array contained URLs like "/w/load.php...only=scripts". These were formatted by getScriptURLsForDebug running on Meta, no longer with a reason to make it a Meta-Wiki URL as it isn't perceived as cross-wiki. It is indistinguishable from debugging a Meta-Wiki page view from its perspective. This patch affects scenario 3 by always expanding it relative to the current-request's wgServer. We still only do this in debug mode. There is not yet a need to do this in non-debug mode, and if there was we'd likely want to find a way to avoid it in the common case to keep embedded URLs short. The ResourceLoader::expandUrl() method is similar to the one in Wikimedia\Minify\CSSMin. Test Plan: * view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=site For Module base class. Before, the array entries were relative. After, they are full. * view-source:http://mw.localhost:8080/w/load.php?debug=1&modules=jquery For FileModule. Before, the array entries were relative. After, they are full. * view-source:http://mw.localhost:8080/wiki/Main_Page?debug=true Unchanged. * view-source:http://mw.localhost:8080/wiki/Main_Page Unchanged. Bug: T255367 Change-Id: I83919744b2677c7fb52b84089ecc60b89957d32a
2021-08-25 02:36:25 +00:00
$urls = [];
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
foreach ( $this->getScriptFiles( $context ) as $file ) {
if ( isset( $file['filePath'] ) ) {
$url = OutputPage::transformResourcePath( $config, $this->getRemotePath( $file['filePath'] ) );
// Expand debug URL in case we are another wiki's module source (T255367)
$url = $rl->expandUrl( $server, $url );
$urls[] = $url;
}
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
}
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() {
// phpcs:ignore Generic.WhiteSpace.LanguageConstructSpacing.IncorrectSingle
return
// Denied by options?
$this->debugRaw
// If package files are involved, don't support URL loading, because that breaks
// scoped require() functions
&& !$this->packageFiles
// Can't link to scripts generated by callbacks
&& !$this->hasGeneratedScripts();
}
public function shouldSkipStructureTest() {
return $this->skipStructureTest || parent::shouldSkipStructureTest();
}
/**
* Determine whether the module may potentially have generated scripts.
*
* @return bool
*/
private function hasGeneratedScripts() {
foreach (
[ $this->scripts, $this->languageScripts, $this->skinScripts, $this->debugScripts ]
as $scripts
) {
foreach ( $scripts as $script ) {
if ( is_array( $script ) ) {
if ( isset( $script['callback'] ) || isset( $script['versionCallback'] ) ) {
return true;
}
}
}
}
return false;
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
}
/**
* Get all styles for a given context.
*
* @param Context $context
* @return string[] CSS code for $context as an associative array mapping media type to CSS text.
*/
public function getStyles( Context $context ) {
$styles = $this->readStyleFiles(
$this->getStyleFiles( $context ),
Revamp classic edit toolbar not to hardcode paths in HTML Also, try out a way to have per-module LESS variables defined in PHP. This might come in handy in the future… Maybe for skin theme support? (I recommend reviewing the file changes in the order below. :D) includes/resourceloader/ResourceLoaderFileModule.php * Pass the context (ResourceLoaderContext) deeper down via readStyleFiles() and readStyleFile(). We need it to compile the .less files for the right language. * Extract LESS compiler creation to getLessCompiler(). * Allow passing a LESS compiler instance to compileLessFile(), rather than getting one after the method is called. All of the changes are backwards-compatible. includes/resourceloader/ResourceLoaderEditToolbarModule.php * New module to support getting the language data and passing it to LESS variables. It might be a good idea to factor out a reusable class for a LESS module with additional variables, but that would require more attention to design than I gave it. resources/src/mediawiki.action/mediawiki.action.edit.toolbar/mediawiki.action.edit.toolbar.less * Glue code to use the language data defined by the module above and put it in final CSS. includes/EditPage.php * Do not hardcode image URLs in output HTML, as they are provided in CSS now. This gets rid of some usage of globals. In fact, we should be able to finally move the inline JavaScript calls out of getEditToolbar(), but I'm already introducing too many changes for one patch. That can be done later. languages/Language.php * Add getImageFiles() to complement existing getImageFile() method. Misleadingly named, it returns paths for images for the toolbar only (and no other ones at all). skins/common/ → resources/src/mediawiki.action/mediawiki.action.edit.toolbar/ * Moved all of the button images to new location. Also, boring cleanup that was harder before because we treated the paths as public API: * Placed default ones in en/ subdirectory. * Renamed cyrl/ to ru/. * Renamed ksh/button_S_italic.png → ksh/button_italic.png. languages/messages/ * Adjusting paths and filenames for the changes above. resources/src/mediawiki.action/mediawiki.action.edit.css resources/src/mediawiki.action/mediawiki.action.edit.js * Added styles and updated the script to make it possible to have non-<img> elements as toolbar buttons. * Consolidated styles that were already required, but defined somewhere else: * `cursor: pointer;` (from shared.css) * `vertical-align: middle;` (from commonElements.css) Bug: 69277 Change-Id: I39d8ed4258c7da0fe4fe4c665cdb26c86420769c
2014-08-20 13:13:43 +00:00
$context
);
$packageFiles = $this->getPackageFiles( $context );
if ( $packageFiles !== null ) {
foreach ( $packageFiles['files'] as $fileName => $file ) {
if ( $file['type'] === 'script+style' ) {
$style = $this->processStyle(
$file['content']['style'],
$file['content']['styleLang'],
$fileName,
$context
);
$styles['all'] = ( $styles['all'] ?? '' ) . "\n" . $style;
}
}
}
// Track indirect file dependencies so that StartUpModule can check for
// on-disk file changes to any of this files without having to recompute the file list
$this->saveFileDependencies( $context, $this->localFileRefs );
return $styles;
}
/**
* @param Context $context
* @return string[][] Lists of URLs by media type
*/
public function getStyleURLsForDebug( Context $context ) {
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
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 = [];
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
foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
$urls[$mediaType] = [];
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
foreach ( $list as $file ) {
$urls[$mediaType][] = OutputPage::transformResourcePath(
$this->getConfig(),
$this->getRemotePath( $file )
);
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
}
}
return $urls;
}
/**
* Get message keys used by this module.
*
* @return string[] List of message keys
*/
public function getMessages() {
return $this->messages;
}
/**
* Get the name of the group this module should be loaded in.
*
* @return null|string Group name
*/
public function getGroup() {
return $this->group;
}
/**
* Get names of modules this module depends on.
*
* @param Context|null $context
* @return string[] List of module names
*/
public function getDependencies( ?Context $context = null ) {
return $this->dependencies;
}
/**
* Helper method for getting a file.
*
* @param string $localPath The path to the resource to load
* @param string $type The type of resource being loaded (for error reporting only)
* @return string
*/
private function getFileContents( $localPath, $type ) {
if ( !is_file( $localPath ) ) {
throw new RuntimeException( "$type file not found or not a file: \"$localPath\"" );
}
return $this->stripBom( file_get_contents( $localPath ) );
}
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
/**
* @return null|string
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
*/
public function getSkipFunction() {
if ( !$this->skipFunction ) {
return null;
}
$localPath = $this->getLocalPath( $this->skipFunction );
return $this->getFileContents( $localPath, 'skip function' );
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
}
public function requiresES6() {
ResourceLoader: Raise MW JavaScript startup requirement to ES6 The UA sniffs that overrode the feature tests are no longer needed. * MSIE 10: Fine, rejected by feature checks. * UC Mini "Speed Mode": Redundant, the version that this sniff matched is pre-ES6. Current versions of UC Mini don't appear to support enabling "Speed Mode" on random websites nor does it offer it for Wikipedia specifically. Details at https://phabricator.wikimedia.org/T178356#8740573. * Google Web Light: Redundant, shutdown as of 2022. Any references or extensions that still reach the proxy, get redirected to our online URLs https://googleweblight.com/?lite_url=https://en.m.wikipedia.org/wiki/Banana https://phabricator.wikimedia.org/T152602 https://en.wikipedia.org/wiki/Google_Web_Light * MeeGo: Redundant, discontinued and presumed rejected. Either way, unsupported. * Opera Mini: Fine, rejected by checks. Details at https://phabricator.wikimedia.org/T178356#8740573. * Ovi Browser: Redundant, discontinued and presumed rejected. Either way, unsupported. * Google Glass: Improve UX (since 2013, T58008). * NetFront: Redundant. Old versions are presumed rejected. Current versions are Chromium-based and presumed fine. The exclusion was not UX based, but due to jQuery explicitly not supporting it in 2013. This is no longer the case, so we can let the feature test lead the way here. * PlayStation: Redundant, same story as NetFront. The version that matched the sniff is presumed rejected. Current versions probably fine, but even not, don't match our sniff so are already enabled today. Bug: T178356 Change-Id: Ib6263ce3ffd11af5e501de8857f3e48a248c6210
2023-03-24 12:56:01 +00:00
return true;
}
resourceloader: Enable module content version for data modules This greatly simplifies logic required to compute module versions. It also makes it significantly less error-prone. Since f37cee996e, we support hashes as versions (instead of timestamps). This means we can build a hash of the content directly, instead of compiling a large array with all values that may influence the module content somehow. Benefits: * Remove all methods and logic related to querying database and disk for timestamps, revision numbers, definition summaries, cache epochs, and more. * No longer needlessly invalidate cache as a result of no-op changes to implementation datails. Due to inclusion of absolute file paths in the definition summary, cache was always invalidated when moving wikis to newer MediaWiki branches; even if the module observed no actual changes. * When changes are reverted within a certain period of time, old caches can now be re-used. The module would produce the same version hash as before. Previously when a change was deployed and then reverted, all web clients (even those that never saw the bad version) would have re-fetch modules because the version increased. Updated unit tests to account for the change in version. New default version of empty test modules is: "mvgTPvXh". For the record, this comes from the base64 encoding of the SHA1 digest of the JSON serialised form of the module content: > $str = '{"scripts":"","styles":{"css":[]},"messagesBlob":"{}"}'; > echo base64_encode(sha1($str, true)); > FEb3+VuiUm/fOMfod1bjw/te+AQ= Enabled content versioning for the data modules in MediaWiki core: * EditToolbarModule * JqueryMsgModule * LanguageDataModule * LanguageNamesModule * SpecialCharacterDataModule * UserCSSPrefsModule * UserDefaultsModule * UserOptionsModule The FileModule and base class explicitly disable it for now and keep their current behaviour of using the definition summary. We may remove it later, but that requires more performance testing first. Explicitly disable it in the WikiModule class to avoid breakage when the default changes. Ref T98087. Change-Id: I782df43c50dfcfb7d7592f744e13a3a0430b0dc6
2015-06-02 17:27:23 +00:00
/**
* Disable module content versioning.
*
* This class uses getDefinitionSummary() instead, to avoid filesystem overhead
* involved with building the full module content inside a startup request.
*
* @return bool
*/
public function enableModuleContentVersion() {
return false;
}
/**
* Helper method for getDefinitionSummary.
*
* @param Context $context
* @return string Hash
*/
private function getFileHashes( Context $context ) {
$files = [];
foreach ( $this->getStyleFiles( $context ) as $filePaths ) {
foreach ( $filePaths as $filePath ) {
$files[] = $this->getLocalPath( $filePath );
}
}
// Extract file paths for package files
// Optimisation: Use foreach() and isset() instead of array_map/array_filter.
// This is a hot code path, called by StartupModule for thousands of modules.
$expandedPackageFiles = $this->expandPackageFiles( $context );
if ( $expandedPackageFiles ) {
foreach ( $expandedPackageFiles['files'] as $fileInfo ) {
$filePath = $fileInfo['filePath'] ?? $fileInfo['versionFilePath'] ?? null;
if ( $filePath instanceof FilePath ) {
$files[] = $filePath->getLocalPath();
}
}
}
// Add other configured paths
$scriptFileInfos = $this->getScriptFiles( $context );
foreach ( $scriptFileInfos as $fileInfo ) {
$filePath = $fileInfo['filePath'] ?? $fileInfo['versionFilePath'] ?? null;
if ( $filePath instanceof FilePath ) {
$files[] = $filePath->getLocalPath();
}
}
foreach ( $this->templates as $filePath ) {
$files[] = $this->getLocalPath( $filePath );
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
}
if ( $this->skipFunction ) {
$files[] = $this->getLocalPath( $this->skipFunction );
}
// Add any lazily discovered file dependencies from previous module builds.
// These are already absolute paths.
foreach ( $this->getFileDependencies( $context ) as $file ) {
$files[] = $file;
}
// Filter out any duplicates. Typically introduced by getFileDependencies() which
// may lazily re-discover a primary file.
$files = array_unique( $files );
// Don't return array keys or any other form of file path here, only the hashes.
// Including file paths would needlessly cause global cache invalidation when files
// move on disk or if e.g. the MediaWiki directory name changes.
// Anything where order is significant is already detected by the definition summary.
return FileContentsHasher::getFileContentsHash( $files );
}
/**
* Get the definition summary for this module.
*
* @param Context $context
* @return array
*/
public function getDefinitionSummary( Context $context ) {
$summary = parent::getDefinitionSummary( $context );
resourceloader: Replace timestamp system with version hashing Modules now track their version via getVersionHash() instead of getModifiedTime(). == Background == While some resources have observeable timestamps (e.g. files stored on disk), many other resources do not. E.g. config variables, and module definitions. For static file modules, one can e.g. revert one of more files in a module to a previous version and not affect the max timestamp. Wiki modules include pages only if they exist. The user module supports common.js and skin.js. By default neither exists. If a user has both, and then the less-recently modified one is deleted, the max-timestamp remains unchanged. For client-side caching, batch requests use "Math.max" on the relevant timestamps. Again, if a module changes but another module is more recent (e.g. out-of-order deployment, or out-of-order discovery), the change would not result in a cache miss. More scenarios can be found in the associated Phabricator tasks. == Version hash == Previously we virtually mapped these variables to a timestamp by storing the current time alongside a hash of the value in ObjectCache. Considering the number of possible request contexts (wikis * modules * users * skins * languages) this doesn't work well. It results in needless cache invalidation when the first time observation is purged due to LRU algorithms. It also has other minor bugs leading to fewer cache hits. All modules automatically get the benefits of version hashing with this change. The old getDefinitionMtime() and getHashMtime() have been replaced with dummies that return 1. These functions are often called from getModifiedTime() in subclasses. For backward-compatibility, their respective values (definition summary and hash) are now included in getVersionHash directly. As examples, the following modules have been updated to use getVersionHash directly. Other modules still work fine and can be updated later. * ResourceLoaderFileModule * ResourceLoaderEditToolbarModule * ResourceLoaderStartUpModule * ResourceLoaderWikiModule The presence of hashes in place of timestamps increases the startup module size on a default MediaWiki install from 4.4k to 5.8k (after gzip and minification). == ETag == Since timestamps are no longer tracked, we need a different way to implement caching for cache proxies (e.g. Varnish) and web browsers. Previously we used the Last-Modified header (in combination with Cache-Control and Expires). Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match). Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default. They instruct browsers to allow usage of partial Range requests. Since our responses are dynamically generated, we need to use the Weak version of ETag. While this sounds bad, it's no different than Last-Modified. As reassured by RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the specified behaviour behind Last-Modified follows the same "Weak" caching logic as Entity tags. It's just that entity tags are capable of a stricter mode (whereas Last-Modified is inherently weak). == File cache == If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache load.php responses. While the blind TTL handling (during the allowed expiry period) is still maxage/timestamp based, tryRespondNotModified() now requires the caller to know the expected ETag. For this to work, the FileCache handling had to be moved from the top of ResoureLoader::respond() to after the expected ETag is computed. This also allows us to remove the duplicate tryRespondNotModified() handling since that's is already handled by ResourceLoader::respond() meanwhile. == Misc == * Remove redundant modifiedTime cache in ResourceLoaderFileModule. * Change bugzilla references to Phabricator. * Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this logic was duplicated in each place the modified timestamp was used. * It's easy to forget calling the parent class in getDefinitionSummary(). Previously this method only tracked 'class' by default. As such, various extensions hardcoded that one value instead of calling the parent and extending the array. To better prevent this in the future, getVersionHash() now asserts that the '_cacheEpoch' property made it through. * tests: Don't use getDefinitionSummary() as an API. Fix ResourceLoaderWikiModuleTest to call getPages properly. * In tests, the default timestamp used to be 1388534400000 (which is the unix time of 20140101000000; the unit tests' CacheEpoch). The new version hash of these modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of: '{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}' * Add sha1.js library for client-side hash generation. Compared various different implementations for code size (after minfication/gzip), and speed (when used for short hexidecimal strings). https://jsperf.com/sha1-implementations - CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k) http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js Chrome: 45k, Firefox: 89k, Safari: 92k - jsSHA <https://github.com/Caligatio/jsSHA> https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k) Chrome: 65k, Firefox: 53k, Safari: 69k - phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k) https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js Chrome: 200k, Firefox: 280k, Safari: 78k Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous, only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being needed in the module loader, we'd have to load the fallback regardless. Considering this is not used in a critical path for performance, it's not worth shipping two implementations for this optimisation. May also resolve: * T44094 * T90411 * T94810 Bug: T94074 Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
$options = [];
foreach ( [
// The following properties are omitted because they don't affect the module response:
// - localBasePath (Per T104950; Changes when absolute directory name changes. If
// this affects 'scripts' and other file paths, getFileHashes accounts for that.)
// - remoteBasePath (Per T104950)
// - dependencies (provided via startup module)
// - group (provided via startup module)
'styles',
'skinStyles',
'messages',
'templates',
resourceloader: Implement "skip function" feature A module can be registered with a skip function. Such function, if provided, will be invoked by the client when a module is queued for loading. If the function returns true, the client will bypass any further loading action and mark the module as 'ready'. This can be used to implement a feature test for a module providing a shim or polyfill. * Change visibility of method ResourceLoader::filter to public. So that it can be invoked by ResourceLoaderStartupModule. * Add option to suppress the cache key report in ResourceLoader::filter. We usually only call the minifier once on an entire request reponse (because it's all concatenated javascript or embedded javascript in various different closures, still valid as one large script) and only add a little bottom line for the cache key. When embedding the skip function we have to run the minifier on them separately as they're output as strings (not actual functions). These strings are typically quite small and blowing up the response with loads of cache keys is not desirable in production. * Add method to clear the static cache of ResourceLoader::inDebugMode. Global static state is evil but, as long as we have it, we at least need to clear it after switching contexts in the test suite. Also: * Remove obsolete setting of 'debug=true' in the FauxRequest in ResourceLoaderTestCase. It already sets global wgResourceLoaderDebug in the setUp() method. Bug: 66390 Change-Id: I87a0ea888d791ad39f114380c42e2daeca470961
2014-04-30 21:06:51 +00:00
'skipFunction',
'debugRaw',
] as $member ) {
resourceloader: Replace timestamp system with version hashing Modules now track their version via getVersionHash() instead of getModifiedTime(). == Background == While some resources have observeable timestamps (e.g. files stored on disk), many other resources do not. E.g. config variables, and module definitions. For static file modules, one can e.g. revert one of more files in a module to a previous version and not affect the max timestamp. Wiki modules include pages only if they exist. The user module supports common.js and skin.js. By default neither exists. If a user has both, and then the less-recently modified one is deleted, the max-timestamp remains unchanged. For client-side caching, batch requests use "Math.max" on the relevant timestamps. Again, if a module changes but another module is more recent (e.g. out-of-order deployment, or out-of-order discovery), the change would not result in a cache miss. More scenarios can be found in the associated Phabricator tasks. == Version hash == Previously we virtually mapped these variables to a timestamp by storing the current time alongside a hash of the value in ObjectCache. Considering the number of possible request contexts (wikis * modules * users * skins * languages) this doesn't work well. It results in needless cache invalidation when the first time observation is purged due to LRU algorithms. It also has other minor bugs leading to fewer cache hits. All modules automatically get the benefits of version hashing with this change. The old getDefinitionMtime() and getHashMtime() have been replaced with dummies that return 1. These functions are often called from getModifiedTime() in subclasses. For backward-compatibility, their respective values (definition summary and hash) are now included in getVersionHash directly. As examples, the following modules have been updated to use getVersionHash directly. Other modules still work fine and can be updated later. * ResourceLoaderFileModule * ResourceLoaderEditToolbarModule * ResourceLoaderStartUpModule * ResourceLoaderWikiModule The presence of hashes in place of timestamps increases the startup module size on a default MediaWiki install from 4.4k to 5.8k (after gzip and minification). == ETag == Since timestamps are no longer tracked, we need a different way to implement caching for cache proxies (e.g. Varnish) and web browsers. Previously we used the Last-Modified header (in combination with Cache-Control and Expires). Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match). Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default. They instruct browsers to allow usage of partial Range requests. Since our responses are dynamically generated, we need to use the Weak version of ETag. While this sounds bad, it's no different than Last-Modified. As reassured by RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the specified behaviour behind Last-Modified follows the same "Weak" caching logic as Entity tags. It's just that entity tags are capable of a stricter mode (whereas Last-Modified is inherently weak). == File cache == If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache load.php responses. While the blind TTL handling (during the allowed expiry period) is still maxage/timestamp based, tryRespondNotModified() now requires the caller to know the expected ETag. For this to work, the FileCache handling had to be moved from the top of ResoureLoader::respond() to after the expected ETag is computed. This also allows us to remove the duplicate tryRespondNotModified() handling since that's is already handled by ResourceLoader::respond() meanwhile. == Misc == * Remove redundant modifiedTime cache in ResourceLoaderFileModule. * Change bugzilla references to Phabricator. * Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this logic was duplicated in each place the modified timestamp was used. * It's easy to forget calling the parent class in getDefinitionSummary(). Previously this method only tracked 'class' by default. As such, various extensions hardcoded that one value instead of calling the parent and extending the array. To better prevent this in the future, getVersionHash() now asserts that the '_cacheEpoch' property made it through. * tests: Don't use getDefinitionSummary() as an API. Fix ResourceLoaderWikiModuleTest to call getPages properly. * In tests, the default timestamp used to be 1388534400000 (which is the unix time of 20140101000000; the unit tests' CacheEpoch). The new version hash of these modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of: '{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}' * Add sha1.js library for client-side hash generation. Compared various different implementations for code size (after minfication/gzip), and speed (when used for short hexidecimal strings). https://jsperf.com/sha1-implementations - CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k) http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js Chrome: 45k, Firefox: 89k, Safari: 92k - jsSHA <https://github.com/Caligatio/jsSHA> https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k) Chrome: 65k, Firefox: 53k, Safari: 69k - phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k) https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js Chrome: 200k, Firefox: 280k, Safari: 78k Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous, only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being needed in the module loader, we'd have to load the fallback regardless. Considering this is not used in a critical path for performance, it's not worth shipping two implementations for this optimisation. May also resolve: * T44094 * T90411 * T94810 Bug: T94074 Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
$options[$member] = $this->{$member};
}
resourceloader: Replace timestamp system with version hashing Modules now track their version via getVersionHash() instead of getModifiedTime(). == Background == While some resources have observeable timestamps (e.g. files stored on disk), many other resources do not. E.g. config variables, and module definitions. For static file modules, one can e.g. revert one of more files in a module to a previous version and not affect the max timestamp. Wiki modules include pages only if they exist. The user module supports common.js and skin.js. By default neither exists. If a user has both, and then the less-recently modified one is deleted, the max-timestamp remains unchanged. For client-side caching, batch requests use "Math.max" on the relevant timestamps. Again, if a module changes but another module is more recent (e.g. out-of-order deployment, or out-of-order discovery), the change would not result in a cache miss. More scenarios can be found in the associated Phabricator tasks. == Version hash == Previously we virtually mapped these variables to a timestamp by storing the current time alongside a hash of the value in ObjectCache. Considering the number of possible request contexts (wikis * modules * users * skins * languages) this doesn't work well. It results in needless cache invalidation when the first time observation is purged due to LRU algorithms. It also has other minor bugs leading to fewer cache hits. All modules automatically get the benefits of version hashing with this change. The old getDefinitionMtime() and getHashMtime() have been replaced with dummies that return 1. These functions are often called from getModifiedTime() in subclasses. For backward-compatibility, their respective values (definition summary and hash) are now included in getVersionHash directly. As examples, the following modules have been updated to use getVersionHash directly. Other modules still work fine and can be updated later. * ResourceLoaderFileModule * ResourceLoaderEditToolbarModule * ResourceLoaderStartUpModule * ResourceLoaderWikiModule The presence of hashes in place of timestamps increases the startup module size on a default MediaWiki install from 4.4k to 5.8k (after gzip and minification). == ETag == Since timestamps are no longer tracked, we need a different way to implement caching for cache proxies (e.g. Varnish) and web browsers. Previously we used the Last-Modified header (in combination with Cache-Control and Expires). Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match). Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default. They instruct browsers to allow usage of partial Range requests. Since our responses are dynamically generated, we need to use the Weak version of ETag. While this sounds bad, it's no different than Last-Modified. As reassured by RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the specified behaviour behind Last-Modified follows the same "Weak" caching logic as Entity tags. It's just that entity tags are capable of a stricter mode (whereas Last-Modified is inherently weak). == File cache == If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache load.php responses. While the blind TTL handling (during the allowed expiry period) is still maxage/timestamp based, tryRespondNotModified() now requires the caller to know the expected ETag. For this to work, the FileCache handling had to be moved from the top of ResoureLoader::respond() to after the expected ETag is computed. This also allows us to remove the duplicate tryRespondNotModified() handling since that's is already handled by ResourceLoader::respond() meanwhile. == Misc == * Remove redundant modifiedTime cache in ResourceLoaderFileModule. * Change bugzilla references to Phabricator. * Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this logic was duplicated in each place the modified timestamp was used. * It's easy to forget calling the parent class in getDefinitionSummary(). Previously this method only tracked 'class' by default. As such, various extensions hardcoded that one value instead of calling the parent and extending the array. To better prevent this in the future, getVersionHash() now asserts that the '_cacheEpoch' property made it through. * tests: Don't use getDefinitionSummary() as an API. Fix ResourceLoaderWikiModuleTest to call getPages properly. * In tests, the default timestamp used to be 1388534400000 (which is the unix time of 20140101000000; the unit tests' CacheEpoch). The new version hash of these modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of: '{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}' * Add sha1.js library for client-side hash generation. Compared various different implementations for code size (after minfication/gzip), and speed (when used for short hexidecimal strings). https://jsperf.com/sha1-implementations - CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k) http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js Chrome: 45k, Firefox: 89k, Safari: 92k - jsSHA <https://github.com/Caligatio/jsSHA> https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k) Chrome: 65k, Firefox: 53k, Safari: 69k - phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k) https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js Chrome: 200k, Firefox: 280k, Safari: 78k Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous, only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being needed in the module loader, we'd have to load the fallback regardless. Considering this is not used in a critical path for performance, it's not worth shipping two implementations for this optimisation. May also resolve: * T44094 * T90411 * T94810 Bug: T94074 Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
$packageFiles = $this->expandPackageFiles( $context );
$packageSummaries = [];
if ( $packageFiles ) {
// Extract the minimum needed:
// - The 'main' pointer (included as-is).
// - The 'files' array, simplified to only which files exist (the keys of
// this array), and something that represents their non-file content.
// For packaged files that reflect files directly from disk, the
// 'getFileHashes' method tracks their content already.
// It is important that the keys of the $packageFiles['files'] array
// are preserved, as they do affect the module output.
foreach ( $packageFiles['files'] as $fileName => $fileInfo ) {
$packageSummaries[$fileName] =
$fileInfo['definitionSummary'] ?? $fileInfo['content'] ?? null;
}
}
$scriptFiles = $this->getScriptFiles( $context );
$scriptSummaries = [];
foreach ( $scriptFiles as $fileName => $fileInfo ) {
$scriptSummaries[$fileName] =
$fileInfo['definitionSummary'] ?? $fileInfo['content'] ?? null;
}
$summary[] = [
resourceloader: Replace timestamp system with version hashing Modules now track their version via getVersionHash() instead of getModifiedTime(). == Background == While some resources have observeable timestamps (e.g. files stored on disk), many other resources do not. E.g. config variables, and module definitions. For static file modules, one can e.g. revert one of more files in a module to a previous version and not affect the max timestamp. Wiki modules include pages only if they exist. The user module supports common.js and skin.js. By default neither exists. If a user has both, and then the less-recently modified one is deleted, the max-timestamp remains unchanged. For client-side caching, batch requests use "Math.max" on the relevant timestamps. Again, if a module changes but another module is more recent (e.g. out-of-order deployment, or out-of-order discovery), the change would not result in a cache miss. More scenarios can be found in the associated Phabricator tasks. == Version hash == Previously we virtually mapped these variables to a timestamp by storing the current time alongside a hash of the value in ObjectCache. Considering the number of possible request contexts (wikis * modules * users * skins * languages) this doesn't work well. It results in needless cache invalidation when the first time observation is purged due to LRU algorithms. It also has other minor bugs leading to fewer cache hits. All modules automatically get the benefits of version hashing with this change. The old getDefinitionMtime() and getHashMtime() have been replaced with dummies that return 1. These functions are often called from getModifiedTime() in subclasses. For backward-compatibility, their respective values (definition summary and hash) are now included in getVersionHash directly. As examples, the following modules have been updated to use getVersionHash directly. Other modules still work fine and can be updated later. * ResourceLoaderFileModule * ResourceLoaderEditToolbarModule * ResourceLoaderStartUpModule * ResourceLoaderWikiModule The presence of hashes in place of timestamps increases the startup module size on a default MediaWiki install from 4.4k to 5.8k (after gzip and minification). == ETag == Since timestamps are no longer tracked, we need a different way to implement caching for cache proxies (e.g. Varnish) and web browsers. Previously we used the Last-Modified header (in combination with Cache-Control and Expires). Instead of Last-Modified (and If-Modified-Since), we use ETag (and If-None-Match). Entity tags (new in HTTP/1.1) are much stricter than Last-Modified by default. They instruct browsers to allow usage of partial Range requests. Since our responses are dynamically generated, we need to use the Weak version of ETag. While this sounds bad, it's no different than Last-Modified. As reassured by RFC 2616 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3> the specified behaviour behind Last-Modified follows the same "Weak" caching logic as Entity tags. It's just that entity tags are capable of a stricter mode (whereas Last-Modified is inherently weak). == File cache == If $wgUseFileCache is enabled, ResourceLoader uses ResourceFileCache to cache load.php responses. While the blind TTL handling (during the allowed expiry period) is still maxage/timestamp based, tryRespondNotModified() now requires the caller to know the expected ETag. For this to work, the FileCache handling had to be moved from the top of ResoureLoader::respond() to after the expected ETag is computed. This also allows us to remove the duplicate tryRespondNotModified() handling since that's is already handled by ResourceLoader::respond() meanwhile. == Misc == * Remove redundant modifiedTime cache in ResourceLoaderFileModule. * Change bugzilla references to Phabricator. * Centralised inclusion of wgCacheEpoch using getDefinitionSummary. Previously this logic was duplicated in each place the modified timestamp was used. * It's easy to forget calling the parent class in getDefinitionSummary(). Previously this method only tracked 'class' by default. As such, various extensions hardcoded that one value instead of calling the parent and extending the array. To better prevent this in the future, getVersionHash() now asserts that the '_cacheEpoch' property made it through. * tests: Don't use getDefinitionSummary() as an API. Fix ResourceLoaderWikiModuleTest to call getPages properly. * In tests, the default timestamp used to be 1388534400000 (which is the unix time of 20140101000000; the unit tests' CacheEpoch). The new version hash of these modules is "XyCC+PSK", which is the base64 encoded prefix of the SHA1 digest of: '{"_class":"ResourceLoaderTestModule","_cacheEpoch":"20140101000000"}' * Add sha1.js library for client-side hash generation. Compared various different implementations for code size (after minfication/gzip), and speed (when used for short hexidecimal strings). https://jsperf.com/sha1-implementations - CryptoJS <https://code.google.com/p/crypto-js/#SHA-1> (min+gzip: 2.5k) http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js Chrome: 45k, Firefox: 89k, Safari: 92k - jsSHA <https://github.com/Caligatio/jsSHA> https://github.com/Caligatio/jsSHA/blob/3c1d4f2e/src/sha1.js (min+gzip: 1.8k) Chrome: 65k, Firefox: 53k, Safari: 69k - phpjs-sha1 <https://github.com/kvz/phpjs> (RL min+gzip: 0.8k) https://github.com/kvz/phpjs/blob/1eaab15d/functions/strings/sha1.js Chrome: 200k, Firefox: 280k, Safari: 78k Modern browsers implement the HTML5 Crypto API. However, this API is asynchronous, only enabled when on HTTPS in Chromium, and is quite low-level. It requires boilerplate code to actually use with TextEncoder, ArrayBuffer and Uint32Array. Due this being needed in the module loader, we'd have to load the fallback regardless. Considering this is not used in a critical path for performance, it's not worth shipping two implementations for this optimisation. May also resolve: * T44094 * T90411 * T94810 Bug: T94074 Change-Id: Ibb292d2416839327d1807a66c78fd96dac0637d0
2015-04-29 22:53:24 +00:00
'options' => $options,
'packageFiles' => $packageSummaries,
'scripts' => $scriptSummaries,
'fileHashes' => $this->getFileHashes( $context ),
resourceloader: Migrate from msg_resource table to object cache MessageBlobStore class: * Make logger aware. * Log an error if json encoding fails. * Stop using the DB table. WANObjectCache supports everything we need: - Batch retrieval. - Invalidate keys with wildcard selects or cascading check keys. * Update tests slightly since the actual update now happens on-demand as part of get() instead of within updateMessage(). ResourceLoader class: * Remove all interaction with the msg_resource table. Remove db table later. * Refactor code to use a hash of the blob instead of a timestamp. Timestamps are unreliable and roll over too frequently for message blob store because there is no authoritative source. The timestamps were inferred based on when a change is observed. Message overrides from the local wiki have an explicit update event when the page is edited. All other messages, such as from MediaWiki core and extensions using LocalisationCache, have a single timestamp for all messages which rolls over every time the cache is rebuilt. A hash is deterministic, and won't cause needless invalidation (T102578). * Remove redundant pre-fetching in makeModuleResponse(). This is already done by preloadModuleInfo() in respond(). * Don't bother storing and retreiving empty "{}" objects. Instead, detect whether a module's message list is empty at runtime. ResourceLoaderModule class: * Make logger aware. * Log if a module's message blob was not preloaded. cleanupRemovedModules: * Now that blobs have a TTL, there's no need to prune old entries. Bug: T113092 Bug: T92357 Change-Id: Id8c26f41a82597e34013f95294cdc3971a4f52ae
2015-11-13 00:04:12 +00:00
'messageBlob' => $this->getMessageBlob( $context ),
];
$lessVars = $this->getLessVars( $context );
if ( $lessVars ) {
$summary[] = [ 'lessVars' => $lessVars ];
}
return $summary;
}
/**
* @return VueComponentParser
*/
protected function getVueComponentParser() {
if ( $this->vueComponentParser === null ) {
$this->vueComponentParser = new VueComponentParser;
}
return $this->vueComponentParser;
}
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
/**
* @param string|FilePath $path
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
* @return string
*/
protected function getPath( $path ) {
if ( $path instanceof FilePath ) {
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
return $path->getPath();
}
return $path;
}
/**
* @param string|FilePath $path
* @return string
*/
protected function getLocalPath( $path ) {
if ( $path instanceof FilePath ) {
if ( $path->getLocalBasePath() !== null ) {
return $path->getLocalPath();
}
$path = $path->getPath();
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
}
return "{$this->localBasePath}/$path";
}
/**
* @param string|FilePath $path
* @return string
*/
protected function getRemotePath( $path ) {
if ( $path instanceof FilePath ) {
if ( $path->getRemoteBasePath() !== null ) {
return $path->getRemotePath();
}
$path = $path->getPath();
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
}
if ( $this->remoteBasePath === '/' ) {
return "/$path";
} else {
return "{$this->remoteBasePath}/$path";
}
}
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
/**
* Infer the stylesheet language from a stylesheet file path.
*
* @since 1.22
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
* @param string $path
* @return string The stylesheet language name
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
*/
public function getStyleSheetLang( $path ) {
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
}
/**
* Infer the file type from a package file path.
*
* @param string $path
* @return string 'script', 'script-vue', or 'data'
*/
public static function getPackageFileType( $path ) {
if ( preg_match( '/\.json$/i', $path ) ) {
return 'data';
}
if ( preg_match( '/\.vue$/i', $path ) ) {
return 'script-vue';
}
return 'script';
}
/**
* Collate style file paths by 'media' option (or 'all' if 'media' is not set)
*
* @param array $list List of file paths in any combination of index/path
* or path/options pairs
* @return string[][] List of collated file paths
*/
private static function collateStyleFilesByMedia( array $list ) {
$collatedFiles = [];
foreach ( $list as $key => $value ) {
if ( is_int( $key ) ) {
// File name as the value
$collatedFiles['all'][] = $value;
} elseif ( is_array( $value ) ) {
// File name as the key, options array as the value
$optionValue = $value['media'] ?? 'all';
$collatedFiles[$optionValue][] = $key;
}
}
return $collatedFiles;
}
/**
* Get 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 $list
* @param string|null $fallback Key to look for in $list if $key doesn't exist
* @return array List of elements from $list 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 [];
}
/**
* Get script file paths for this module, in order of proper execution.
*
* @param Context $context
* @return array An array of file info arrays as returned by expandFileInfo()
*/
private function getScriptFiles( Context $context ): array {
// List in execution order: scripts, languageScripts, skinScripts, debugScripts.
// Documented at MediaWiki\MainConfigSchema::ResourceModules.
$filesByCategory = [
'scripts' => $this->scripts,
'languageScripts' => $this->getLanguageScripts( $context->getLanguage() ),
'skinScripts' => self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
];
if ( $context->getDebug() ) {
$filesByCategory['debugScripts'] = $this->debugScripts;
}
$expandedFiles = [];
foreach ( $filesByCategory as $category => $files ) {
foreach ( $files as $key => $fileInfo ) {
$expandedFileInfo = $this->expandFileInfo( $context, $fileInfo, "$category\[$key]" );
$expandedFiles[$expandedFileInfo['name']] = $expandedFileInfo;
}
}
return $expandedFiles;
}
/**
* Get the set of language scripts for the given language,
* possibly using a fallback language.
*
* @param string $lang
* @return array<int,string|FilePath> File paths
*/
private function getLanguageScripts( string $lang ): array {
$scripts = self::tryForKey( $this->languageScripts, $lang );
if ( $scripts ) {
return $scripts;
}
// Optimization: Avoid initialising and calling into language services
// for the majority of modules that don't use this option.
if ( $this->languageScripts ) {
$fallbacks = MediaWikiServices::getInstance()
->getLanguageFallback()
->getAll( $lang, LanguageFallback::MESSAGES );
foreach ( $fallbacks as $lang ) {
$scripts = self::tryForKey( $this->languageScripts, $lang );
if ( $scripts ) {
return $scripts;
}
}
}
return [];
}
public function setSkinStylesOverride( array $moduleSkinStyles ): void {
$moduleName = $this->getName();
foreach ( $moduleSkinStyles as $skinName => $overrides ) {
// If a module provides overrides for a skin, and that skin also provides overrides
// for the same module, then the module has precedence.
if ( isset( $this->skinStyles[$skinName] ) ) {
continue;
}
// If $moduleName in ResourceModuleSkinStyles is preceded with a '+', the defined style
// files will be added to 'default' skinStyles, otherwise 'default' will be ignored.
if ( isset( $overrides[$moduleName] ) ) {
$paths = (array)$overrides[$moduleName];
$styleFiles = [];
} elseif ( isset( $overrides['+' . $moduleName] ) ) {
$paths = (array)$overrides['+' . $moduleName];
$styleFiles = isset( $this->skinStyles['default'] ) ?
(array)$this->skinStyles['default'] :
[];
} else {
continue;
}
// Add new file paths, remapping them to refer to our directories and not use settings
// from the module we're modifying, which come from the base definition.
[ $localBasePath, $remoteBasePath ] = self::extractBasePaths( $overrides );
foreach ( $paths as $path ) {
$styleFiles[] = new FilePath( $path, $localBasePath, $remoteBasePath );
}
$this->skinStyles[$skinName] = $styleFiles;
}
}
/**
* Get a list of file paths for all styles in this module, in order of proper inclusion.
*
* @internal Exposed only for use by structure phpunit tests.
* @param Context $context
* @return array<string,array<int,string|FilePath>> Map from media type to list of file paths
*/
public function getStyleFiles( Context $context ) {
return array_merge_recursive(
self::collateStyleFilesByMedia( $this->styles ),
self::collateStyleFilesByMedia(
self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' )
)
);
}
/**
* Get a list of file paths for all skin styles in the module used by
* the skin.
*
* @param string $skinName The name of the skin
* @return array A list of file paths collated by media type
*/
protected function getSkinStyleFiles( $skinName ) {
return self::collateStyleFilesByMedia(
self::tryForKey( $this->skinStyles, $skinName )
);
}
/**
* Get a list of file paths for all skin style files in the module,
* for all available skins.
*
* @return array A list of file paths collated by media type
*/
protected function getAllSkinStyleFiles() {
$skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
$styleFiles = [];
$internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
$internalSkinNames[] = 'default';
foreach ( $internalSkinNames as $internalSkinName ) {
$styleFiles = array_merge_recursive(
$styleFiles,
$this->getSkinStyleFiles( $internalSkinName )
);
}
return $styleFiles;
}
/**
* Get all style files and all skin style files used by this module.
*
* @return array
*/
public function getAllStyleFiles() {
$collatedStyleFiles = array_merge_recursive(
self::collateStyleFilesByMedia( $this->styles ),
$this->getAllSkinStyleFiles()
);
$result = [];
foreach ( $collatedStyleFiles as $styleFiles ) {
foreach ( $styleFiles as $styleFile ) {
$result[] = $this->getLocalPath( $styleFile );
}
}
return $result;
}
/**
* Read the contents of a list of CSS files and remap and concatenate these.
*
* @internal This is considered a private method. Exposed for internal use by WebInstallerOutput.
* @param array<string,array<int,string|FilePath>> $styles Map of media type to file paths
* @param Context $context
* @return array<string,string> Map of combined CSS code, keyed by media type
*/
public function readStyleFiles( array $styles, Context $context ) {
if ( !$styles ) {
return [];
}
foreach ( $styles as $media => $files ) {
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
$uniqueFiles = array_unique( $files, SORT_REGULAR );
$styleFiles = [];
foreach ( $uniqueFiles as $file ) {
$styleFiles[] = $this->readStyleFile( $file, $context );
}
$styles[$media] = implode( "\n", $styleFiles );
}
return $styles;
}
/**
* Read and process a style file. Reads a file from disk and runs it through processStyle().
*
* This method can be used as a callback for array_map()
*
* @internal
* @param string|FilePath $path Path of style file to read
* @param Context $context
* @return string CSS code
*/
protected function readStyleFile( $path, Context $context ) {
$localPath = $this->getLocalPath( $path );
$style = $this->getFileContents( $localPath, 'style' );
$styleLang = $this->getStyleSheetLang( $localPath );
return $this->processStyle( $style, $styleLang, $path, $context );
}
/**
* Process a CSS/LESS string.
*
* This method performs the following processing steps:
* - LESS compilation (if $styleLang = 'less')
* - RTL flipping with CSSJanus (if getFlip() returns true)
* - Registration of references to local files in $localFileRefs and $missingLocalFileRefs
* - URL remapping and data URI embedding
*
* @internal
* @param string $style CSS or LESS code
* @param string $styleLang Language of $style code ('css' or 'less')
* @param string|FilePath $path Path to code file, used for resolving relative file paths
* @param Context $context
* @return string Processed CSS code
*/
protected function processStyle( $style, $styleLang, $path, Context $context ) {
$localPath = $this->getLocalPath( $path );
$remotePath = $this->getRemotePath( $path );
if ( $styleLang === 'less' ) {
$style = $this->compileLessString( $style, $localPath, $context );
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
$this->hasGeneratedStyles = true;
}
if ( $this->getFlip( $context ) ) {
$style = CSSJanus::transform(
$style,
/* $swapLtrRtlInURL = */ true,
/* $swapLeftRightInURL = */ false
);
$this->hasGeneratedStyles = true;
}
resourceloader: Allow skins to provide additional styles for any module The newly introduced $wgResourceModuleSkinStyles global enables skins to provide additional stylesheets to existing ResourceLoader module. This both makes it easier (or at all possible) to override default styles and lowers the style footprint by making it possible not to load styles unused on most pages. ---- Example: Use the file 'foo-styles.css' for the 'mediawiki.foo' module when using the MySkin skin: $wgResourceModuleSkinStyles['myskin'] = array( 'mediawiki.foo' => 'foo-styles.css', 'remoteSkinPath' => 'MySkin', 'localBasePath' => __DIR__, ); For detailed documentation, see the doc comment in DefaultSettings.php. For a practical usage example, see Vector.php. ---- Implementation notes: * The values defined in $wgResourceModuleSkinStyles are embedded into the modules as late as possible (in ResourceLoader::register()). * Only plain file modules are supported, setting module skin styles for other module types has no effect. * ResourceLoader and ResourceLoaderFileModule now support loading files from arbitrary paths to make this possible, defined using ResourceLoaderFilePath objects. * This required some adjustments in seemingly unrelated places for code which didn't handle the paths fully correctly before. * ResourceLoader and ResourceLoaderFileModule are now a bit more tightly coupled than before :( * Included a tiny example change for the Vector skin, a lot more of similar cleanup is possible and planned for the future. * Many of the non-essential mediawiki.* modules defined in Resources.php should be using `'skinStyles' => array( 'default' => … )` instead of `'styles' => …` to allow more customizations, this is also planned for the future after auditing which ones would actually benefit from this. Change-Id: Ica4ff9696b490e35f60288d7ce1295766c427e87
2014-06-26 14:29:31 +00:00
$localDir = dirname( $localPath );
$remoteDir = dirname( $remotePath );
// Get and register local file references
$localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
foreach ( $localFileRefs as $file ) {
if ( is_file( $file ) ) {
$this->localFileRefs[] = $file;
} else {
$this->missingLocalFileRefs[] = $file;
}
}
// Don't cache this call. remap() ensures data URIs embeds are up to date,
// and urls contain correct content hashes in their query string. (T128668)
return CSSMin::remap( $style, $localDir, $remoteDir, true );
}
/**
* Get whether CSS for this module should be flipped
* @param Context $context
* @return bool
*/
public function getFlip( Context $context ) {
return $context->getDirection() === 'rtl' && !$this->noflip;
}
/**
* Get the module's load type.
*
* @since 1.28
* @return string
*/
public function getType() {
$canBeStylesOnly = !(
// All options except 'styles', 'skinStyles' and 'debugRaw'
$this->scripts
|| $this->debugScripts
|| $this->templates
|| $this->languageScripts
|| $this->skinScripts
|| $this->dependencies
|| $this->messages
|| $this->skipFunction
|| $this->packageFiles
);
return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
}
/**
* Compile a LESS string into CSS.
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
*
* Keeps track of all used files and adds them to localFileRefs.
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
*
* @since 1.35
* @param string $style LESS source to compile
* @param string $stylePath File path of LESS source, used for resolving relative file paths
* @param Context $context Context in which to generate script
* @return string CSS source
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
*/
protected function compileLessString( $style, $stylePath, Context $context ) {
static $cache;
// @TODO: dependency injection
if ( !$cache ) {
$cache = MediaWikiServices::getInstance()->getObjectCacheFactory()
->getLocalServerInstance( CACHE_ANYTHING );
}
$skinName = $context->getSkin();
$skinImportPaths = ExtensionRegistry::getInstance()->getAttribute( 'SkinLessImportPaths' );
$importDirs = [];
if ( isset( $skinImportPaths[ $skinName ] ) ) {
$importDirs[] = $skinImportPaths[ $skinName ];
}
$vars = $this->getLessVars( $context );
// Construct a cache key from a hash of the LESS source, and a hash digest
Codex: Allow a local development version to be used Developers can use this to test their local version of Codex with MediaWiki by pointing $wgCodexDevelopmentDir to their local clone of the Codex repo, e.g. $wgCodexDevelopmentDir = '/home/yourname/git/codex'; Setting $wgCodexDevelopmentDir affects where the following things come from: - Codex JS/CSS files for the full library - Codex JS/CSS files for code-split chunks, and the manifest.json file that points to them - Icons retrieved by CodexModule::getIcons() - CSS-only icons imported in Less - Design tokens imported in Less Other changes in this patch: - Add CodexModule::makeFilePath() to centralize the repeated path concatenation. This makes it easier to switch out the regular path for the dev mode path. - Replace all uses of $IP (which is deprecated) and MW_INSTALL_PATH in CodexModule with the BaseDirectory config setting. - Make CodexModule::getIcons() reset its static cache if the path to the icons file changes. Without this, it's impossible to make the unit tests pass. - Move the i18n messages code from the CodexModule constructor to getMessages(). It can't be in the constructor because makeFilePath() doesn't work there (it fails because the Config object hasn't been set up yet). - Add a 'mediawiki.skin.codex' import path so that we can stop hard-coding the path to the Codex mixins file. Without this, we can't make the Codex mixins come from the right place in development mode. - Consider $wgCodexDevelopmentDir in setting the cache key for compiled Less code, since changing this setting can change the output of Less compilation (by changing design tokens, icons or mixins). - Add unit tests for (the non-dev mode behavior of) CodexModule::getIcons() and the i18n message key handling. Bug: T314507 Change-Id: I11c6a81a1ba34fe10f4b1c98bf76f0db40c1ce98
2024-05-02 03:27:22 +00:00
// of the LESS variables and import dirs used for compilation.
2015-09-25 17:57:35 +00:00
ksort( $vars );
$compilerParams = [
'vars' => $vars,
'importDirs' => $importDirs,
Codex: Allow a local development version to be used Developers can use this to test their local version of Codex with MediaWiki by pointing $wgCodexDevelopmentDir to their local clone of the Codex repo, e.g. $wgCodexDevelopmentDir = '/home/yourname/git/codex'; Setting $wgCodexDevelopmentDir affects where the following things come from: - Codex JS/CSS files for the full library - Codex JS/CSS files for code-split chunks, and the manifest.json file that points to them - Icons retrieved by CodexModule::getIcons() - CSS-only icons imported in Less - Design tokens imported in Less Other changes in this patch: - Add CodexModule::makeFilePath() to centralize the repeated path concatenation. This makes it easier to switch out the regular path for the dev mode path. - Replace all uses of $IP (which is deprecated) and MW_INSTALL_PATH in CodexModule with the BaseDirectory config setting. - Make CodexModule::getIcons() reset its static cache if the path to the icons file changes. Without this, it's impossible to make the unit tests pass. - Move the i18n messages code from the CodexModule constructor to getMessages(). It can't be in the constructor because makeFilePath() doesn't work there (it fails because the Config object hasn't been set up yet). - Add a 'mediawiki.skin.codex' import path so that we can stop hard-coding the path to the Codex mixins file. Without this, we can't make the Codex mixins come from the right place in development mode. - Consider $wgCodexDevelopmentDir in setting the cache key for compiled Less code, since changing this setting can change the output of Less compilation (by changing design tokens, icons or mixins). - Add unit tests for (the non-dev mode behavior of) CodexModule::getIcons() and the i18n message key handling. Bug: T314507 Change-Id: I11c6a81a1ba34fe10f4b1c98bf76f0db40c1ce98
2024-05-02 03:27:22 +00:00
// CodexDevelopmentDir affects import path mapping in ResourceLoader::getLessCompiler(),
// so take that into account too
'codexDevDir' => $this->getConfig()->get( MainConfigNames::CodexDevelopmentDir )
];
$key = $cache->makeGlobalKey(
'resourceloader-less',
'v1',
hash( 'md4', $style ),
hash( 'md4', serialize( $compilerParams ) )
);
// If we got a cached value, we have to validate it by getting a checksum of all the
// files that were loaded by the parser and ensuring it matches the cached entry's.
$data = $cache->get( $key );
if (
!$data ||
$data['hash'] !== FileContentsHasher::getFileContentsHash( $data['files'] )
) {
$compiler = $context->getResourceLoader()->getLessCompiler( $vars, $importDirs );
$css = $compiler->parse( $style, $stylePath )->getCss();
// T253055: store the implicit dependency paths in a form relative to any install
// path so that multiple version of the application can share the cache for identical
// less stylesheets. This also avoids churn during application updates.
$files = $compiler->getParsedFiles();
$data = [
'css' => $css,
'files' => Module::getRelativePaths( $files ),
'hash' => FileContentsHasher::getFileContentsHash( $files )
];
$cache->set( $key, $data, $cache::TTL_DAY );
}
foreach ( Module::expandRelativePaths( $data['files'] ) as $path ) {
$this->localFileRefs[] = $path;
}
return $data['css'];
Support LESS stylesheets in ResourceLoader This patch adds support for the LESS stylesheet language to ResourceLoader. LESS is a stylesheet language that compiles into CSS. The patch includes lessphp, a LESS compiler implemented in PHP. The rationale for choosing LESS is explained in a MediaWiki RFC which accompanies this patch, available at <https://www.mediawiki.org/wiki/Requests_for_comment/LESS>. LESS support is provided for ResourceLoader file modules. It is triggered by the presence of the '.less' extension in stylesheet filenames. LESS files are compiled by lessc, and the resultant CSS is subjected to the standard set of transformations (CSSJanus & CSSMin). The immediate result of LESS compilation is encoded as an array, which includes the list of LESS files that were compiled and their mtimes. This array is cached. Cache invalidation is performed by comparing the cached mtimes with the mtimes of the files on disk. If the compiler itself throws an exception, ResourceLoader constructs a compilation result which consists of the error message encoded as a CSS comment. Failed compilation results are cached too, but with an expiration time of five minutes. The expiration time is required because the full list of referenced files is not known. Three configuration variables configure the global environment for LESS modules: $wgResourceLoaderLESSVars, $wgResourceLoaderLESSFunctions, and $wgResourceLoaderLESSImportPaths. $wgResourceLoaderLESSVars maps variable names to CSS values, specified as strings. Variables declared in this array are available in all LESS files. $wgResourceLoaderLESSFunctions is similar, except it maps custom function names to PHP callables. These functions can be called from within LESS to transform values. Read more about custom functions at <http://leafo.net/lessphp/docs/#custom_functions>. Finally, $wgResourceLoaderLESSImportPaths specifies file system paths in addition to the current module's path where the LESS compiler should look up files referenced in @import statements. The issue of handling of /* @embed */ and /* @noflip */ annotations is left unresolved. Earlier versions of this patch included an @embed analog implemented as a LESS custom function, but there was enough ambiguity about whether the strategy it took was optimal to merit discussing it in a separate, follow-up patch. Bug: 40964 Change-Id: Id052a04dd2f76a1f4aef39fbd454bd67f5fd282f
2013-08-11 16:40:20 +00:00
}
Revamp classic edit toolbar not to hardcode paths in HTML Also, try out a way to have per-module LESS variables defined in PHP. This might come in handy in the future… Maybe for skin theme support? (I recommend reviewing the file changes in the order below. :D) includes/resourceloader/ResourceLoaderFileModule.php * Pass the context (ResourceLoaderContext) deeper down via readStyleFiles() and readStyleFile(). We need it to compile the .less files for the right language. * Extract LESS compiler creation to getLessCompiler(). * Allow passing a LESS compiler instance to compileLessFile(), rather than getting one after the method is called. All of the changes are backwards-compatible. includes/resourceloader/ResourceLoaderEditToolbarModule.php * New module to support getting the language data and passing it to LESS variables. It might be a good idea to factor out a reusable class for a LESS module with additional variables, but that would require more attention to design than I gave it. resources/src/mediawiki.action/mediawiki.action.edit.toolbar/mediawiki.action.edit.toolbar.less * Glue code to use the language data defined by the module above and put it in final CSS. includes/EditPage.php * Do not hardcode image URLs in output HTML, as they are provided in CSS now. This gets rid of some usage of globals. In fact, we should be able to finally move the inline JavaScript calls out of getEditToolbar(), but I'm already introducing too many changes for one patch. That can be done later. languages/Language.php * Add getImageFiles() to complement existing getImageFile() method. Misleadingly named, it returns paths for images for the toolbar only (and no other ones at all). skins/common/ → resources/src/mediawiki.action/mediawiki.action.edit.toolbar/ * Moved all of the button images to new location. Also, boring cleanup that was harder before because we treated the paths as public API: * Placed default ones in en/ subdirectory. * Renamed cyrl/ to ru/. * Renamed ksh/button_S_italic.png → ksh/button_italic.png. languages/messages/ * Adjusting paths and filenames for the changes above. resources/src/mediawiki.action/mediawiki.action.edit.css resources/src/mediawiki.action/mediawiki.action.edit.js * Added styles and updated the script to make it possible to have non-<img> elements as toolbar buttons. * Consolidated styles that were already required, but defined somewhere else: * `cursor: pointer;` (from shared.css) * `vertical-align: middle;` (from commonElements.css) Bug: 69277 Change-Id: I39d8ed4258c7da0fe4fe4c665cdb26c86420769c
2014-08-20 13:13:43 +00:00
/**
* Get content of named templates for this module.
*
* @return array<string,string> Templates mapping template alias to content
*/
public function getTemplates() {
$templates = [];
foreach ( $this->templates as $alias => $templatePath ) {
// Alias is optional
if ( is_int( $alias ) ) {
Allow skins/extensions to define custom OOUI themes This change follows I39cc2a735d9625c87bf4ede6f5fb0ec441d47dcc. docs/extension.schema.v1.json docs/extension.schema.v2.json includes/registration/ExtensionProcessor.php * The new extension attribute 'OOUIThemePaths' can be used to define custom OOUI themes. See I9187a63e509b601b8558ea82850fa828e5c8cc0a for an example usage. includes/resourceloader/ResourceLoaderOOUIModule.php * Add support for 'OOUIThemePaths'. * Defining 'images' is now optional. I figure custom themes are unlikely to have or need them. * Use ResourceLoaderFilePath objects to allow skin-/extension-defined OOUI module files to use skin/extension's base paths. This was previously used to support $wgResourceModuleSkinStyles, but only for 'skinStyles' - now ResourceLoaderFileModule needs to also handle it for 'skinScripts', and ResourceLoaderImageModule for 'images'). includes/resourceloader/ResourceLoaderFilePath.php * Add getters for local/remote base paths, for when we need to construct a new ResourceLoaderFilePath based on existing one. includes/resourceloader/ResourceLoaderFileModule.php includes/resourceloader/ResourceLoaderImageModule.php includes/resourceloader/ResourceLoaderOOUIImageModule.php * Add or improve handling of ResourceLoaderFilePaths: * Replace `(array)` casts with explicit array wrapping, to avoid casting objects into associative arrays. * Use getLocalPath() instead of string concatenation. tests/phpunit/includes/resourceloader/ResourceLoaderFileModuleTest.php tests/phpunit/includes/resourceloader/ResourceLoaderImageModuleTest.php * Some basic checks for the above. Bug: T100896 Change-Id: I74362f0fc215b26f1f104ce7bdbbac1e106736ad
2017-03-17 02:14:05 +00:00
$alias = $this->getPath( $templatePath );
}
$localPath = $this->getLocalPath( $templatePath );
$content = $this->getFileContents( $localPath, 'template' );
$templates[$alias] = $this->stripBom( $content );
}
return $templates;
}
/**
* Internal helper for use by getPackageFiles(), getFileHashes() and getDefinitionSummary().
*
* This expands the 'packageFiles' definition into something that's (almost) the right format
* for getPackageFiles() to return. It expands shorthands, resolves config vars, and handles
* summarising any non-file data for getVersionHash(). For file-based data, getFileHashes()
* handles it instead, which also ends up in getDefinitionSummary().
*
* What it does not do is reading the actual contents of any specified files, nor invoking
* the computation callbacks. Those things are done by getPackageFiles() instead to improve
* backend performance by only doing this work when the module response is needed, and not
* when merely computing the version hash for StartupModule, or when checking
* If-None-Match headers for a HTTP 304 response.
*
* @param Context $context
* @return array|null Array of arrays as returned by expandFileInfo(), with the key being
* the file name, or null if this is not a package file module.
* @phan-return array{main:?string,files:array[]}|null
*/
private function expandPackageFiles( Context $context ) {
$hash = $context->getHash();
if ( isset( $this->expandedPackageFiles[$hash] ) ) {
return $this->expandedPackageFiles[$hash];
}
if ( $this->packageFiles === null ) {
return null;
}
$expandedFiles = [];
$mainFile = null;
foreach ( $this->packageFiles as $key => $fileInfo ) {
$expanded = $this->expandFileInfo( $context, $fileInfo, "packageFiles[$key]" );
$fileName = $expanded['name'];
if ( !empty( $expanded['main'] ) ) {
unset( $expanded['main'] );
$type = $expanded['type'];
$mainFile = $fileName;
if ( $type !== 'script' && $type !== 'script-vue' ) {
$msg = "Main file in package must be of type 'script', module " .
"'{$this->getName()}', main file '{$mainFile}' is '{$type}'.";
$this->getLogger()->error( $msg );
throw new LogicException( $msg );
}
}
$expandedFiles[$fileName] = $expanded;
}
if ( $expandedFiles && $mainFile === null ) {
// The first package file that is a script is the main file
foreach ( $expandedFiles as $path => $file ) {
if ( $file['type'] === 'script' || $file['type'] === 'script-vue' ) {
$mainFile = $path;
break;
}
}
}
$result = [
'main' => $mainFile,
'files' => $expandedFiles
];
$this->expandedPackageFiles[$hash] = $result;
return $result;
}
/**
* Process a file info array as specified in configuration or extension.json,
* expanding shortcuts and callbacks.
*
* @see MainConfigSchema::ResourceModules
*
* @param Context $context
* @param array|string|FilePath $fileInfo
* @param string $debugKey
* @return array An associative array with the following keys:
* - name: (string) The filename relative to the module base. This is unique only within
* the context of the current module. It may be a virtual name.
* - type: (string) May be 'script', 'script-vue', 'data' or 'text'
* - filePath: (FilePath) The FilePath object which should be used to load the content.
* This will be absent if the content was loaded another way.
* - virtualFilePath: (FilePath) A FilePath object for a virtual path which doesn't actually
* exist. This is used for source map generation. Optional.
* - versionFilePath: (FilePath) A FilePath object which is the ultimate source of a
* generated file. The timestamp and contents will be used for version generation.
* Generated by the callback specified in versionCallback. Optional.
* - content: (string|mixed) If the 'type' element is 'script', this is a string containing
* JS code, being the contents of the script file. For any other type, this contains data
* which will be JSON serialized. Optional, if not set, it will be set in readFileInfo().
* - callback: (callable) A callback to call to obtain the contents. This will be set if the
* version callback was present in the input, indicating that the callback is expensive.
* - callbackParam: (array) The parameters to be passed to the callback.
* - definitionSummary: (array) The data returned by the version callback.
* - main: (bool) Whether the file is the main file of the package.
*/
private function expandFileInfo( Context $context, $fileInfo, $debugKey ) {
if ( is_string( $fileInfo ) ) {
// Inline common case
return [
'name' => $fileInfo,
'type' => self::getPackageFileType( $fileInfo ),
'filePath' => new FilePath( $fileInfo, $this->localBasePath, $this->remoteBasePath )
];
} elseif ( $fileInfo instanceof FilePath ) {
$fileInfo = [
'name' => $fileInfo->getPath(),
'file' => $fileInfo
];
} elseif ( !is_array( $fileInfo ) ) {
$msg = "Invalid type in $debugKey for module '{$this->getName()}', " .
"must be array, string or FilePath";
$this->getLogger()->error( $msg );
throw new LogicException( $msg );
}
if ( !isset( $fileInfo['name'] ) ) {
$msg = "Missing 'name' key in $debugKey for module '{$this->getName()}'";
$this->getLogger()->error( $msg );
throw new LogicException( $msg );
}
$fileName = $this->getPath( $fileInfo['name'] );
// Infer type from alias if needed
$type = $fileInfo['type'] ?? self::getPackageFileType( $fileName );
$expanded = [
'name' => $fileName,
'type' => $type
];
if ( !empty( $fileInfo['main'] ) ) {
$expanded['main'] = true;
}
// Perform expansions (except 'file' and 'callback'), creating one of these keys:
// - 'content': literal value.
// - 'filePath': content to be read from a file.
// - 'callback': content computed by a callable.
if ( isset( $fileInfo['content'] ) ) {
$expanded['content'] = $fileInfo['content'];
} elseif ( isset( $fileInfo['file'] ) ) {
$expanded['filePath'] = $this->makeFilePath( $fileInfo['file'] );
} elseif ( isset( $fileInfo['callback'] ) ) {
// If no extra parameter for the callback is given, use null.
$expanded['callbackParam'] = $fileInfo['callbackParam'] ?? null;
if ( !is_callable( $fileInfo['callback'] ) ) {
$msg = "Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
$this->getLogger()->error( $msg );
throw new LogicException( $msg );
}
if ( isset( $fileInfo['versionCallback'] ) ) {
if ( !is_callable( $fileInfo['versionCallback'] ) ) {
throw new LogicException( "Invalid 'versionCallback' for "
. "module '{$this->getName()}', file '{$fileName}'."
);
}
// Execute the versionCallback with the same arguments that
// would be given to the callback
$callbackResult = ( $fileInfo['versionCallback'] )(
$context,
$this->getConfig(),
$expanded['callbackParam']
);
if ( $callbackResult instanceof FilePath ) {
$callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
$expanded['versionFilePath'] = $callbackResult;
} else {
$expanded['definitionSummary'] = $callbackResult;
}
// Don't invoke 'callback' here as it may be expensive (T223260).
$expanded['callback'] = $fileInfo['callback'];
} else {
// Else go ahead invoke callback with its arguments.
$callbackResult = ( $fileInfo['callback'] )(
$context,
$this->getConfig(),
$expanded['callbackParam']
);
if ( $callbackResult instanceof FilePath ) {
$callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
$expanded['filePath'] = $callbackResult;
} else {
$expanded['content'] = $callbackResult;
}
}
} elseif ( isset( $fileInfo['config'] ) ) {
if ( $type !== 'data' ) {
$msg = "Key 'config' only valid for data files. "
. " Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
$this->getLogger()->error( $msg );
throw new LogicException( $msg );
}
$expandedConfig = [];
foreach ( $fileInfo['config'] as $configKey => $var ) {
$expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
}
$expanded['content'] = $expandedConfig;
} elseif ( !empty( $fileInfo['main'] ) ) {
// [ 'name' => 'foo.js', 'main' => true ] is shorthand
$expanded['filePath'] = $this->makeFilePath( $fileName );
} else {
$msg = "Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
. "One of 'file', 'content', 'callback', or 'config' must be set.";
$this->getLogger()->error( $msg );
throw new LogicException( $msg );
}
if ( !isset( $expanded['filePath'] ) ) {
$expanded['virtualFilePath'] = $this->makeFilePath( $fileName );
}
return $expanded;
}
/**
* Cast a FilePath or string to a FilePath
*
* @param FilePath|string $path
* @return FilePath
*/
private function makeFilePath( $path ): FilePath {
if ( $path instanceof FilePath ) {
return $path;
} elseif ( is_string( $path ) ) {
return new FilePath( $path, $this->localBasePath, $this->remoteBasePath );
} else {
throw new InvalidArgumentException( '$path must be either FilePath or string' );
}
}
/**
* Resolve the package files definition and generate the content of each package file.
*
* @param Context $context
* @return array|null Package files data structure, see Module::getScript()
*/
public function getPackageFiles( Context $context ) {
if ( $this->packageFiles === null ) {
return null;
}
$hash = $context->getHash();
if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
return $this->fullyExpandedPackageFiles[ $hash ];
}
$expandedPackageFiles = $this->expandPackageFiles( $context ) ?? [];
foreach ( $expandedPackageFiles['files'] as &$fileInfo ) {
$this->readFileInfo( $context, $fileInfo );
}
$this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
return $expandedPackageFiles;
}
/**
* Given a file info array as returned by expandFileInfo(), expand the file paths and
* remaining callbacks, ensuring that the 'content' element is populated. Modify
* the array by reference, removing intermediate data such as callback parameters.
*
* @param Context $context
* @param array &$fileInfo
*/
private function readFileInfo( Context $context, array &$fileInfo ) {
// Turn any 'filePath' or 'callback' key into actual 'content',
// and remove the key after that. The callback could return a
// FilePath object; if that happens, fall through to the 'filePath'
// handling.
if ( !isset( $fileInfo['content'] ) && isset( $fileInfo['callback'] ) ) {
$callbackResult = ( $fileInfo['callback'] )(
$context,
$this->getConfig(),
$fileInfo['callbackParam']
);
if ( $callbackResult instanceof FilePath ) {
// Fall through to the filePath handling code below
$fileInfo['filePath'] = $callbackResult;
} else {
$fileInfo['content'] = $callbackResult;
}
unset( $fileInfo['callback'] );
}
// Only interpret 'filePath' if 'content' hasn't been set already.
// This can happen if 'versionCallback' provided 'filePath',
// while 'callback' provides 'content'. In that case both are set
// at this point. The 'filePath' from 'versionCallback' in that case is
// only to inform getDefinitionSummary().
if ( !isset( $fileInfo['content'] ) && isset( $fileInfo['filePath'] ) ) {
$localPath = $this->getLocalPath( $fileInfo['filePath'] );
$content = $this->getFileContents( $localPath, 'package' );
if ( $fileInfo['type'] === 'data' ) {
$content = json_decode( $content, false, 512, JSON_THROW_ON_ERROR );
}
$fileInfo['content'] = $content;
}
if ( $fileInfo['type'] === 'script-vue' ) {
try {
$parsedComponent = $this->getVueComponentParser()->parse(
// @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
$fileInfo['content'],
[ 'minifyTemplate' => !$context->getDebug() ]
);
} catch ( TimeoutException $e ) {
throw $e;
} catch ( Exception $e ) {
$msg = "Error parsing file '{$fileInfo['name']}' in module '{$this->getName()}': " .
$e->getMessage();
$this->getLogger()->error( $msg );
throw new RuntimeException( $msg );
}
$encodedTemplate = json_encode( $parsedComponent['template'] );
if ( $context->getDebug() ) {
// Replace \n (backslash-n) with space + backslash-n + backslash-newline in debug mode
// The \n has to be preserved to prevent Vue parser issues (T351771)
// We only replace \n if not preceded by a backslash, to avoid breaking '\\n'
$encodedTemplate = preg_replace( '/(?<!\\\\)\\\\n/', " \\n\\\n", $encodedTemplate );
// Expand \t to real tabs in debug mode
$encodedTemplate = strtr( $encodedTemplate, [ "\\t" => "\t" ] );
}
$fileInfo['content'] = [
'script' => $parsedComponent['script'] .
";\nmodule.exports.template = $encodedTemplate;",
'style' => $parsedComponent['style'] ?? '',
'styleLang' => $parsedComponent['styleLang'] ?? 'css'
];
$fileInfo['type'] = 'script+style';
}
if ( !isset( $fileInfo['content'] ) ) {
// This should not be possible due to validation in expandFileInfo()
$msg = "Unable to resolve contents for file {$fileInfo['name']}";
$this->getLogger()->error( $msg );
throw new RuntimeException( $msg );
}
// Not needed for client response, exists for use by getDefinitionSummary().
unset( $fileInfo['definitionSummary'] );
// Not needed for client response, used by callbacks only.
unset( $fileInfo['callbackParam'] );
}
/**
* Take an input string and remove the UTF-8 BOM character if present
*
* We need to remove these after reading a file, because we concatenate our files and
* the BOM character is not valid in the middle of a string.
* We already assume UTF-8 everywhere, so this should be safe.
*
* @param string $input
* @return string Input minus the initial BOM char
*/
protected function stripBom( $input ) {
if ( str_starts_with( $input, "\xef\xbb\xbf" ) ) {
return substr( $input, 3 );
}
return $input;
}
}