29 use InvalidArgumentException;
37 use Wikimedia\Minify\CSSMin;
38 use Wikimedia\RequestTimeout\TimeoutException;
103 private $expandedPackageFiles = [];
109 private $fullyExpandedPackageFiles = [];
181 $hasTemplates =
false;
188 foreach ( $options as $member => $option ) {
195 $this->{$member} = is_array( $option ) ? $option : [ $option ];
198 $hasTemplates =
true;
199 $this->{$member} = is_array( $option ) ? $option : [ $option ];
202 case 'languageScripts':
205 if ( !is_array( $option ) ) {
206 throw new InvalidArgumentException(
207 "Invalid collated file path list error. " .
208 "'$option' given, array expected."
211 foreach ( $option as $key => $value ) {
212 if ( !is_string( $key ) ) {
213 throw new InvalidArgumentException(
214 "Invalid collated file path list key error. " .
215 "'$key' given, string expected."
218 $this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
222 $this->deprecated = $option;
229 $option = array_values( array_unique( (array)$option ) );
232 $this->{$member} = $option;
237 $this->{$member} = (string)$option;
243 $this->{$member} = (bool)$option;
247 if ( isset( $options[
'scripts'] ) && isset( $options[
'packageFiles'] ) ) {
248 throw new InvalidArgumentException(
"A module may not set both 'scripts' and 'packageFiles'" );
250 if ( isset( $options[
'packageFiles'] ) && isset( $options[
'skinScripts'] ) ) {
251 throw new InvalidArgumentException(
"Options 'skinScripts' and 'packageFiles' cannot be used together." );
253 if ( $hasTemplates ) {
254 $this->dependencies[] =
'mediawiki.template';
256 foreach ( $this->templates as $alias => $templatePath ) {
257 if ( is_int( $alias ) ) {
258 $alias = $this->
getPath( $templatePath );
260 $suffix = explode(
'.', $alias );
261 $suffix = end( $suffix );
262 $compilerModule =
'mediawiki.template.' . $suffix;
263 if ( $suffix !==
'html' && !in_array( $compilerModule, $this->dependencies ) ) {
264 $this->dependencies[] = $compilerModule;
295 if ( isset( $options[
'remoteExtPath'] ) ) {
298 $remoteBasePath = $extensionAssetsPath .
'/' . $options[
'remoteExtPath'];
301 if ( isset( $options[
'remoteSkinPath'] ) ) {
307 if ( array_key_exists(
'localBasePath', $options ) ) {
311 if ( array_key_exists(
'remoteBasePath', $options ) ) {
341 if (
$file[
'type'] ===
'script+style' ) {
342 $file[
'content'] =
$file[
'content'][
'script'];
343 $file[
'type'] =
'script';
346 if ( $deprecationScript ) {
348 $mainFile[
'content'] = $deprecationScript . $mainFile[
'content'];
353 $files = $this->getScriptFiles( $context );
354 return $deprecationScript . $this->readScriptFiles( $files );
367 foreach ( $this->getScriptFiles( $context ) as
$file ) {
370 $url = $rl->expandUrl( $server, $url );
400 if (
$file[
'type'] ===
'script+style' ) {
402 $file[
'content'][
'style'],
403 $file[
'content'][
'styleLang'],
424 if ( $this->hasGeneratedStyles ) {
427 return parent::getStyleURLsForDebug( $context );
432 foreach ( $this->
getStyleFiles( $context ) as $mediaType => $list ) {
433 $urls[$mediaType] = [];
434 foreach ( $list as
$file ) {
479 private function getFileContents( $localPath,
$type ) {
480 if ( !is_file( $localPath ) ) {
481 throw new RuntimeException(
"$type file not found or not a file: \"$localPath\"" );
483 return $this->
stripBom( file_get_contents( $localPath ) );
490 if ( !$this->skipFunction ) {
493 $localPath = $this->
getLocalPath( $this->skipFunction );
494 return $this->getFileContents( $localPath,
'skip function' );
519 private function getFileHashes(
Context $context ) {
523 foreach ( $styleFiles as $paths ) {
524 $files = array_merge( $files, $paths );
530 $expandedPackageFiles = $this->expandPackageFiles( $context );
532 if ( $expandedPackageFiles ) {
533 foreach ( $expandedPackageFiles[
'files'] as $fileInfo ) {
534 if ( isset( $fileInfo[
'filePath'] ) ) {
542 $files = array_merge(
547 $context->
getDebug() ? $this->debugScripts : [],
548 $this->getLanguageScripts( $context->
getLanguage() ),
549 self::tryForKey( $this->skinScripts, $context->
getSkin(),
'default' )
551 if ( $this->skipFunction ) {
556 $files = array_map( [ $this,
'getLocalPath' ], $files );
564 $files = array_unique( $files );
580 $summary = parent::getDefinitionSummary( $context );
602 $options[$member] = $this->{$member};
615 $packageFiles[
'files'] = array_map(
static function ( $fileInfo ) {
616 return $fileInfo[
'definitionSummary'] ?? ( $fileInfo[
'content'] ?? null );
621 'options' => $options,
623 'fileHashes' => $this->getFileHashes( $context ),
629 $summary[] = [
'lessVars' => $lessVars ];
639 if ( $this->vueComponentParser ===
null ) {
651 return $path->getPath();
663 if (
$path->getLocalBasePath() !==
null ) {
664 return $path->getLocalPath();
669 return "{$this->localBasePath}/$path";
678 if (
$path->getRemoteBasePath() !==
null ) {
679 return $path->getRemotePath();
684 if ( $this->remoteBasePath ===
'/' ) {
687 return "{$this->remoteBasePath}/$path";
699 return preg_match(
'/\.less$/i',
$path ) ?
'less' :
'css';
708 if ( preg_match(
'/\.json$/i',
$path ) ) {
711 if ( preg_match(
'/\.vue$/i',
$path ) ) {
724 private static function collateStyleFilesByMedia( array $list ) {
726 foreach ( $list as $key => $value ) {
727 if ( is_int( $key ) ) {
729 $collatedFiles[
'all'][] = $value;
730 } elseif ( is_array( $value ) ) {
732 $optionValue = $value[
'media'] ??
'all';
733 $collatedFiles[$optionValue][] = $key;
736 return $collatedFiles;
749 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
766 private function getScriptFiles(
Context $context ): array {
769 $files = array_merge(
771 $this->getLanguageScripts( $context->getLanguage() ),
772 self::
tryForKey( $this->skinScripts, $context->getSkin(),
'default' )
775 $files = array_merge( $files, $this->debugScripts );
778 return array_unique( $files, SORT_REGULAR );
788 private function getLanguageScripts(
string $lang ): array {
789 $scripts = self::tryForKey( $this->languageScripts,
$lang );
796 if ( $this->languageScripts ) {
798 ->getLanguageFallback()
800 foreach ( $fallbacks as
$lang ) {
801 $scripts = self::tryForKey( $this->languageScripts,
$lang );
812 $moduleName = $this->getName();
813 foreach ( $moduleSkinStyles as $skinName => $overrides ) {
816 if ( isset( $this->skinStyles[$skinName] ) ) {
822 if ( isset( $overrides[$moduleName] ) ) {
823 $paths = (array)$overrides[$moduleName];
825 } elseif ( isset( $overrides[
'+' . $moduleName] ) ) {
826 $paths = (array)$overrides[
'+' . $moduleName];
827 $styleFiles = isset( $this->skinStyles[
'default'] ) ?
828 (array)$this->skinStyles[
'default'] :
836 [ $localBasePath, $remoteBasePath ] = self::extractBasePaths( $overrides );
838 foreach ( $paths as
$path ) {
839 $styleFiles[] =
new FilePath(
$path, $localBasePath, $remoteBasePath );
842 $this->skinStyles[$skinName] = $styleFiles;
854 return array_merge_recursive(
855 self::collateStyleFilesByMedia( $this->styles ),
856 self::collateStyleFilesByMedia(
857 self::tryForKey( $this->skinStyles, $context->
getSkin(),
'default' )
870 return self::collateStyleFilesByMedia(
871 self::tryForKey( $this->skinStyles, $skinName )
882 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
885 $internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
886 $internalSkinNames[] =
'default';
888 foreach ( $internalSkinNames as $internalSkinName ) {
889 $styleFiles = array_merge_recursive(
891 $this->getSkinStyleFiles( $internalSkinName )
904 $collatedStyleFiles = array_merge_recursive(
905 self::collateStyleFilesByMedia( $this->styles ),
906 $this->getAllSkinStyleFiles()
911 foreach ( $collatedStyleFiles as $styleFiles ) {
912 foreach ( $styleFiles as $styleFile ) {
913 $result[] = $this->getLocalPath( $styleFile );
926 private function readScriptFiles( array $scripts ) {
931 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
932 $localPath = $this->getLocalPath( $fileName );
933 $contents = $this->getFileContents( $localPath,
'script' );
934 $js .= ResourceLoader::ensureNewline( $contents );
951 foreach ( $styles as $media => $files ) {
952 $uniqueFiles = array_unique( $files, SORT_REGULAR );
954 foreach ( $uniqueFiles as
$file ) {
955 $styleFiles[] = $this->readStyleFile(
$file, $context );
957 $styles[$media] = implode(
"\n", $styleFiles );
973 $localPath = $this->getLocalPath(
$path );
974 $style = $this->getFileContents( $localPath,
'style' );
975 $styleLang = $this->getStyleSheetLang( $localPath );
977 return $this->processStyle( $style, $styleLang,
$path, $context );
997 $localPath = $this->getLocalPath(
$path );
998 $remotePath = $this->getRemotePath(
$path );
1000 if ( $styleLang ===
'less' ) {
1001 $style = $this->compileLessString( $style, $localPath, $context );
1002 $this->hasGeneratedStyles =
true;
1005 if ( $this->getFlip( $context ) ) {
1006 $style = CSSJanus::transform(
1013 $localDir = dirname( $localPath );
1014 $remoteDir = dirname( $remotePath );
1016 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
1017 foreach ( $localFileRefs as
$file ) {
1018 if ( is_file(
$file ) ) {
1019 $this->localFileRefs[] =
$file;
1021 $this->missingLocalFileRefs[] =
$file;
1026 return CSSMin::remap( $style, $localDir, $remoteDir,
true );
1035 return $context->
getDirection() ===
'rtl' && !$this->noflip;
1044 return $this->targets;
1054 $canBeStylesOnly = !(
1057 || $this->debugScripts
1059 || $this->languageScripts
1060 || $this->skinScripts
1061 || $this->dependencies
1063 || $this->skipFunction
1064 || $this->packageFiles
1066 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
1087 $skinName = $context->
getSkin();
1090 if ( isset( $skinImportPaths[ $skinName ] ) ) {
1091 $importDirs[] = $skinImportPaths[ $skinName ];
1094 $vars = $this->getLessVars( $context );
1100 'importDirs' => $importDirs,
1102 $key = $cache->makeGlobalKey(
1103 'resourceloader-less',
1105 hash(
'md4', $style ),
1106 hash(
'md4', serialize( $compilerParams ) )
1111 $data = $cache->get( $key );
1116 $compiler = $context->
getResourceLoader()->getLessCompiler( $vars, $importDirs );
1118 $css = $compiler->parse( $style, $stylePath )->getCss();
1122 $files = $compiler->AllParsedFiles();
1125 'files' => Module::getRelativePaths( $files ),
1128 $cache->set( $key, $data, $cache::TTL_DAY );
1131 foreach ( Module::expandRelativePaths( $data[
'files'] ) as
$path ) {
1132 $this->localFileRefs[] =
$path;
1135 return $data[
'css'];
1146 foreach ( $this->templates as $alias => $templatePath ) {
1148 if ( is_int( $alias ) ) {
1149 $alias = $this->getPath( $templatePath );
1151 $localPath = $this->getLocalPath( $templatePath );
1152 $content = $this->getFileContents( $localPath,
'template' );
1154 $templates[$alias] = $this->stripBom(
$content );
1177 private function expandPackageFiles(
Context $context ) {
1179 if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1180 return $this->expandedPackageFiles[$hash];
1182 if ( $this->packageFiles ===
null ) {
1185 $expandedFiles = [];
1188 foreach ( $this->packageFiles as $key => $fileInfo ) {
1189 if ( !is_array( $fileInfo ) ) {
1190 $fileInfo = [
'name' => $fileInfo,
'file' => $fileInfo ];
1192 if ( !isset( $fileInfo[
'name'] ) ) {
1193 $msg =
"Missing 'name' key in package file info for module '{$this->getName()}'," .
1194 " offset '{$key}'.";
1195 $this->getLogger()->error( $msg );
1196 throw new LogicException( $msg );
1198 $fileName = $this->getPath( $fileInfo[
'name'] );
1201 $type = $fileInfo[
'type'] ?? self::getPackageFileType( $fileName );
1202 $expanded = [
'type' =>
$type ];
1203 if ( !empty( $fileInfo[
'main'] ) ) {
1204 $mainFile = $fileName;
1205 if (
$type !==
'script' &&
$type !==
'script-vue' ) {
1206 $msg =
"Main file in package must be of type 'script', module " .
1207 "'{$this->getName()}', main file '{$mainFile}' is '{$type}'.";
1208 $this->getLogger()->error( $msg );
1209 throw new LogicException( $msg );
1217 if ( isset( $fileInfo[
'content'] ) ) {
1218 $expanded[
'content'] = $fileInfo[
'content'];
1219 } elseif ( isset( $fileInfo[
'file'] ) ) {
1220 $expanded[
'filePath'] = $fileInfo[
'file'];
1221 } elseif ( isset( $fileInfo[
'callback'] ) ) {
1223 $expanded[
'callbackParam'] = $fileInfo[
'callbackParam'] ??
null;
1225 if ( !is_callable( $fileInfo[
'callback'] ) ) {
1226 $msg =
"Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
1227 $this->getLogger()->error( $msg );
1228 throw new LogicException( $msg );
1230 if ( isset( $fileInfo[
'versionCallback'] ) ) {
1231 if ( !is_callable( $fileInfo[
'versionCallback'] ) ) {
1232 throw new LogicException(
"Invalid 'versionCallback' for "
1233 .
"module '{$this->getName()}', file '{$fileName}'."
1239 $callbackResult = ( $fileInfo[
'versionCallback'] )(
1242 $expanded[
'callbackParam']
1244 if ( $callbackResult instanceof FilePath ) {
1245 $expanded[
'filePath'] = $callbackResult;
1247 $expanded[
'definitionSummary'] = $callbackResult;
1250 $expanded[
'callback'] = $fileInfo[
'callback'];
1253 $callbackResult = ( $fileInfo[
'callback'] )(
1256 $expanded[
'callbackParam']
1258 if ( $callbackResult instanceof FilePath ) {
1259 $expanded[
'filePath'] = $callbackResult;
1261 $expanded[
'content'] = $callbackResult;
1264 } elseif ( isset( $fileInfo[
'config'] ) ) {
1265 if (
$type !==
'data' ) {
1266 $msg =
"Key 'config' only valid for data files. "
1267 .
" Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
1268 $this->getLogger()->error( $msg );
1269 throw new LogicException( $msg );
1271 $expandedConfig = [];
1272 foreach ( $fileInfo[
'config'] as $configKey => $var ) {
1273 $expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
1275 $expanded[
'content'] = $expandedConfig;
1276 } elseif ( !empty( $fileInfo[
'main'] ) ) {
1278 $expanded[
'filePath'] = $fileName;
1280 $msg =
"Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
1281 .
"One of 'file', 'content', 'callback', or 'config' must be set.";
1282 $this->getLogger()->error( $msg );
1283 throw new LogicException( $msg );
1286 $expandedFiles[$fileName] = $expanded;
1289 if ( $expandedFiles && $mainFile ===
null ) {
1291 foreach ( $expandedFiles as
$path =>
$file ) {
1292 if (
$file[
'type'] ===
'script' ||
$file[
'type'] ===
'script-vue' ) {
1300 'main' => $mainFile,
1301 'files' => $expandedFiles
1304 $this->expandedPackageFiles[$hash] = $result;
1315 if ( $this->packageFiles ===
null ) {
1319 if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
1320 return $this->fullyExpandedPackageFiles[ $hash ];
1322 $expandedPackageFiles = $this->expandPackageFiles( $context );
1325 foreach ( $expandedPackageFiles[
'files'] as $fileName => &$fileInfo ) {
1330 if ( isset( $fileInfo[
'callback'] ) ) {
1331 $callbackResult = ( $fileInfo[
'callback'] )(
1334 $fileInfo[
'callbackParam']
1336 if ( $callbackResult instanceof
FilePath ) {
1338 $fileInfo[
'filePath'] = $callbackResult;
1340 $fileInfo[
'content'] = $callbackResult;
1342 unset( $fileInfo[
'callback'] );
1349 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'filePath'] ) ) {
1350 $localPath = $this->getLocalPath( $fileInfo[
'filePath'] );
1351 $content = $this->getFileContents( $localPath,
'package' );
1352 if ( $fileInfo[
'type'] ===
'data' ) {
1356 unset( $fileInfo[
'filePath'] );
1358 if ( $fileInfo[
'type'] ===
'script-vue' ) {
1360 $parsedComponent = $this->getVueComponentParser()->parse(
1362 $fileInfo[
'content'],
1363 [
'minifyTemplate' => !$context->
getDebug() ]
1365 }
catch ( TimeoutException $e ) {
1367 }
catch ( Exception $e ) {
1368 $msg =
"Error parsing file '$fileName' in module '{$this->getName()}': " .
1370 $this->getLogger()->error( $msg );
1371 throw new RuntimeException( $msg );
1373 $encodedTemplate = json_encode( $parsedComponent[
'template'] );
1377 $encodedTemplate = preg_replace(
'/(?<!\\\\)\\\\n/',
" \\\n", $encodedTemplate );
1379 $encodedTemplate = strtr( $encodedTemplate, [
"\\t" =>
"\t" ] );
1381 $fileInfo[
'content'] = [
1382 'script' => $parsedComponent[
'script'] .
1383 ";\nmodule.exports.template = $encodedTemplate;",
1384 'style' => $parsedComponent[
'style'] ??
'',
1385 'styleLang' => $parsedComponent[
'styleLang'] ??
'css'
1387 $fileInfo[
'type'] =
'script+style';
1391 unset( $fileInfo[
'definitionSummary'] );
1393 unset( $fileInfo[
'callbackParam'] );
1396 $this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
1397 return $expandedPackageFiles;
1411 if ( str_starts_with( $input,
"\xef\xbb\xbf" ) ) {
1412 return substr( $input, 3 );
1419 class_alias( FileModule::class,
'ResourceLoaderFileModule' );
if(!defined( 'MEDIAWIKI')) if(ini_get( 'mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
The Registry loads JSON files, and uses a Processor to extract information from them.
static getFileContentsHash( $filePaths)
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
A class containing constants representing the names of configuration variables.
const StylePath
Name constant for the StylePath setting, for use with Config::get()
const ExtensionAssetsPath
Name constant for the ExtensionAssetsPath setting, for use with Config::get()
const Server
Name constant for the Server setting, for use with Config::get()
const ResourceBasePath
Name constant for the ResourceBasePath setting, for use with Config::get()
Context object that contains information about the state of a specific ResourceLoader web request.
getHash()
All factors that uniquely identify this request, except 'modules'.
Functions to get cache objects.
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from configuration)
This is one of the Core classes and should be read at least once by any new developers.
static transformResourcePath(Config $config, $path)
Transform path to web-accessible static resource.
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!isset( $args[0])) $lang