28use InvalidArgumentException;
36use Wikimedia\Minify\CSSMin;
37use Wikimedia\RequestTimeout\TimeoutException;
102 private $expandedPackageFiles = [];
108 private $fullyExpandedPackageFiles = [];
177 $hasTemplates =
false;
184 foreach ( $options as $member => $option ) {
191 $this->{$member} = is_array( $option ) ? $option : [ $option ];
194 $hasTemplates =
true;
195 $this->{$member} = is_array( $option ) ? $option : [ $option ];
198 case 'languageScripts':
201 if ( !is_array( $option ) ) {
202 throw new InvalidArgumentException(
203 "Invalid collated file path list error. " .
204 "'$option' given, array expected."
207 foreach ( $option as $key => $value ) {
208 if ( !is_string( $key ) ) {
209 throw new InvalidArgumentException(
210 "Invalid collated file path list key error. " .
211 "'$key' given, string expected."
214 $this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
218 $this->deprecated = $option;
224 $option = array_values( array_unique( (array)$option ) );
227 $this->{$member} = $option;
232 $this->{$member} = (string)$option;
237 case 'skipStructureTest':
238 $this->{$member} = (bool)$option;
242 if ( isset( $options[
'scripts'] ) && isset( $options[
'packageFiles'] ) ) {
243 throw new InvalidArgumentException(
"A module may not set both 'scripts' and 'packageFiles'" );
245 if ( isset( $options[
'packageFiles'] ) && isset( $options[
'skinScripts'] ) ) {
246 throw new InvalidArgumentException(
"Options 'skinScripts' and 'packageFiles' cannot be used together." );
248 if ( $hasTemplates ) {
249 $this->dependencies[] =
'mediawiki.template';
251 foreach ( $this->templates as $alias => $templatePath ) {
252 if ( is_int( $alias ) ) {
253 $alias = $this->
getPath( $templatePath );
255 $suffix = explode(
'.', $alias );
256 $suffix = end( $suffix );
257 $compilerModule =
'mediawiki.template.' . $suffix;
258 if ( $suffix !==
'html' && !in_array( $compilerModule, $this->dependencies ) ) {
259 $this->dependencies[] = $compilerModule;
287 if ( isset( $options[
'remoteExtPath'] ) ) {
290 $remoteBasePath = $extensionAssetsPath .
'/' . $options[
'remoteExtPath'];
293 if ( isset( $options[
'remoteSkinPath'] ) ) {
299 if ( array_key_exists(
'localBasePath', $options ) ) {
303 if ( array_key_exists(
'remoteBasePath', $options ) ) {
330 if ( $file[
'type'] ===
'script+style' ) {
331 $file[
'content'] = $file[
'content'][
'script'];
332 $file[
'type'] =
'script';
338 $files = $this->getScriptFiles( $context );
339 foreach ( $files as &$file ) {
340 $this->readFileInfo( $context, $file );
342 return [
'plainScripts' => $files ];
355 && !$this->packageFiles
357 && !$this->hasGeneratedScripts();
361 return $this->skipStructureTest || parent::shouldSkipStructureTest();
369 private function hasGeneratedScripts() {
371 [ $this->scripts, $this->languageScripts, $this->skinScripts, $this->debugScripts ]
375 if ( is_array( $script ) ) {
376 if ( isset( $script[
'callback'] ) || isset( $script[
'versionCallback'] ) ) {
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 ) {
435 $urls[$mediaType][] = OutputPage::transformResourcePath(
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 ( $filePaths as $filePath ) {
531 $expandedPackageFiles = $this->expandPackageFiles( $context );
532 if ( $expandedPackageFiles ) {
533 foreach ( $expandedPackageFiles[
'files'] as $fileInfo ) {
534 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
535 if ( $filePath instanceof FilePath ) {
536 $files[] = $filePath->getLocalPath();
542 $scriptFileInfos = $this->getScriptFiles( $context );
543 foreach ( $scriptFileInfos as $fileInfo ) {
544 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
545 if ( $filePath instanceof FilePath ) {
546 $files[] = $filePath->getLocalPath();
550 foreach ( $this->templates as $filePath ) {
554 if ( $this->skipFunction ) {
566 $files = array_unique( $files );
582 $summary = parent::getDefinitionSummary( $context );
599 $options[$member] = $this->{$member};
603 $packageSummaries = [];
613 foreach (
$packageFiles[
'files'] as $fileName => $fileInfo ) {
614 $packageSummaries[$fileName] =
615 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
619 $scriptFiles = $this->getScriptFiles( $context );
620 $scriptSummaries = [];
621 foreach ( $scriptFiles as $fileName => $fileInfo ) {
622 $scriptSummaries[$fileName] =
623 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
627 'options' => $options,
628 'packageFiles' => $packageSummaries,
629 'scripts' => $scriptSummaries,
630 'fileHashes' => $this->getFileHashes( $context ),
636 $summary[] = [
'lessVars' => $lessVars ];
646 if ( $this->vueComponentParser ===
null ) {
658 return $path->getPath();
670 if (
$path->getLocalBasePath() !==
null ) {
671 return $path->getLocalPath();
676 return "{$this->localBasePath}/$path";
685 if (
$path->getRemoteBasePath() !==
null ) {
686 return $path->getRemotePath();
691 if ( $this->remoteBasePath ===
'/' ) {
694 return "{$this->remoteBasePath}/$path";
706 return preg_match(
'/\.less$/i',
$path ) ?
'less' :
'css';
716 if ( preg_match(
'/\.json$/i',
$path ) ) {
719 if ( preg_match(
'/\.vue$/i',
$path ) ) {
732 private static function collateStyleFilesByMedia( array $list ) {
734 foreach ( $list as $key => $value ) {
735 if ( is_int( $key ) ) {
737 $collatedFiles[
'all'][] = $value;
738 } elseif ( is_array( $value ) ) {
740 $optionValue = $value[
'media'] ??
'all';
741 $collatedFiles[$optionValue][] = $key;
744 return $collatedFiles;
757 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
774 private function getScriptFiles(
Context $context ): array {
778 'scripts' => $this->scripts,
779 'languageScripts' => $this->getLanguageScripts( $context->getLanguage() ),
780 'skinScripts' => self::
tryForKey( $this->skinScripts, $context->getSkin(),
'default' ),
787 foreach ( $filesByCategory as $category => $files ) {
788 foreach ( $files as $key => $fileInfo ) {
789 $expandedFileInfo = $this->expandFileInfo( $context, $fileInfo,
"$category\[$key]" );
790 $expandedFiles[$expandedFileInfo[
'name']] = $expandedFileInfo;
794 return $expandedFiles;
804 private function getLanguageScripts(
string $lang ): array {
805 $scripts = self::tryForKey( $this->languageScripts, $lang );
812 if ( $this->languageScripts ) {
814 ->getLanguageFallback()
815 ->getAll( $lang, LanguageFallback::MESSAGES );
816 foreach ( $fallbacks as $lang ) {
817 $scripts = self::tryForKey( $this->languageScripts, $lang );
828 $moduleName = $this->getName();
829 foreach ( $moduleSkinStyles as $skinName => $overrides ) {
832 if ( isset( $this->skinStyles[$skinName] ) ) {
838 if ( isset( $overrides[$moduleName] ) ) {
839 $paths = (array)$overrides[$moduleName];
841 } elseif ( isset( $overrides[
'+' . $moduleName] ) ) {
842 $paths = (array)$overrides[
'+' . $moduleName];
843 $styleFiles = isset( $this->skinStyles[
'default'] ) ?
844 (array)$this->skinStyles[
'default'] :
852 [ $localBasePath, $remoteBasePath ] = self::extractBasePaths( $overrides );
854 foreach ( $paths as
$path ) {
855 $styleFiles[] =
new FilePath(
$path, $localBasePath, $remoteBasePath );
858 $this->skinStyles[$skinName] = $styleFiles;
870 return array_merge_recursive(
871 self::collateStyleFilesByMedia( $this->styles ),
872 self::collateStyleFilesByMedia(
873 self::tryForKey( $this->skinStyles, $context->
getSkin(),
'default' )
886 return self::collateStyleFilesByMedia(
887 self::tryForKey( $this->skinStyles, $skinName )
898 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
901 $internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
902 $internalSkinNames[] =
'default';
904 foreach ( $internalSkinNames as $internalSkinName ) {
905 $styleFiles = array_merge_recursive(
907 $this->getSkinStyleFiles( $internalSkinName )
920 $collatedStyleFiles = array_merge_recursive(
921 self::collateStyleFilesByMedia( $this->styles ),
922 $this->getAllSkinStyleFiles()
927 foreach ( $collatedStyleFiles as $styleFiles ) {
928 foreach ( $styleFiles as $styleFile ) {
929 $result[] = $this->getLocalPath( $styleFile );
948 foreach ( $styles as $media => $files ) {
949 $uniqueFiles = array_unique( $files, SORT_REGULAR );
951 foreach ( $uniqueFiles as $file ) {
952 $styleFiles[] = $this->readStyleFile( $file, $context );
954 $styles[$media] = implode(
"\n", $styleFiles );
970 $localPath = $this->getLocalPath(
$path );
971 $style = $this->getFileContents( $localPath,
'style' );
972 $styleLang = $this->getStyleSheetLang( $localPath );
974 return $this->processStyle( $style, $styleLang,
$path, $context );
994 $localPath = $this->getLocalPath(
$path );
995 $remotePath = $this->getRemotePath(
$path );
997 if ( $styleLang ===
'less' ) {
998 $style = $this->compileLessString( $style, $localPath, $context );
999 $this->hasGeneratedStyles =
true;
1002 if ( $this->getFlip( $context ) ) {
1003 $style = CSSJanus::transform(
1008 $this->hasGeneratedStyles =
true;
1011 $localDir = dirname( $localPath );
1012 $remoteDir = dirname( $remotePath );
1014 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
1015 foreach ( $localFileRefs as $file ) {
1016 if ( is_file( $file ) ) {
1017 $this->localFileRefs[] = $file;
1019 $this->missingLocalFileRefs[] = $file;
1024 return CSSMin::remap( $style, $localDir, $remoteDir,
true );
1033 return $context->
getDirection() ===
'rtl' && !$this->noflip;
1043 $canBeStylesOnly = !(
1046 || $this->debugScripts
1048 || $this->languageScripts
1049 || $this->skinScripts
1050 || $this->dependencies
1052 || $this->skipFunction
1053 || $this->packageFiles
1055 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
1073 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()
1077 $skinName = $context->
getSkin();
1078 $skinImportPaths = ExtensionRegistry::getInstance()->getAttribute(
'SkinLessImportPaths' );
1080 if ( isset( $skinImportPaths[ $skinName ] ) ) {
1081 $importDirs[] = $skinImportPaths[ $skinName ];
1084 $vars = $this->getLessVars( $context );
1090 'importDirs' => $importDirs,
1093 'codexDevDir' => $this->getConfig()->get( MainConfigNames::CodexDevelopmentDir )
1095 $key = $cache->makeGlobalKey(
1096 'resourceloader-less',
1098 hash(
'md4', $style ),
1099 hash(
'md4', serialize( $compilerParams ) )
1104 $data = $cache->get( $key );
1107 $data[
'hash'] !== FileContentsHasher::getFileContentsHash( $data[
'files'] )
1109 $compiler = $context->
getResourceLoader()->getLessCompiler( $vars, $importDirs );
1111 $css = $compiler->parse( $style, $stylePath )->getCss();
1115 $files = $compiler->getParsedFiles();
1118 'files' => Module::getRelativePaths( $files ),
1119 'hash' => FileContentsHasher::getFileContentsHash( $files )
1121 $cache->set( $key, $data, $cache::TTL_DAY );
1124 foreach ( Module::expandRelativePaths( $data[
'files'] ) as
$path ) {
1125 $this->localFileRefs[] =
$path;
1128 return $data[
'css'];
1139 foreach ( $this->templates as $alias => $templatePath ) {
1141 if ( is_int( $alias ) ) {
1142 $alias = $this->getPath( $templatePath );
1144 $localPath = $this->getLocalPath( $templatePath );
1145 $content = $this->getFileContents( $localPath,
'template' );
1147 $templates[$alias] = $this->stripBom( $content );
1171 private function expandPackageFiles(
Context $context ) {
1173 if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1174 return $this->expandedPackageFiles[$hash];
1176 if ( $this->packageFiles ===
null ) {
1179 $expandedFiles = [];
1182 foreach ( $this->packageFiles as $key => $fileInfo ) {
1183 $expanded = $this->expandFileInfo( $context, $fileInfo,
"packageFiles[$key]" );
1184 $fileName = $expanded[
'name'];
1185 if ( !empty( $expanded[
'main'] ) ) {
1186 unset( $expanded[
'main'] );
1187 $type = $expanded[
'type'];
1188 $mainFile = $fileName;
1189 if ( $type !==
'script' && $type !==
'script-vue' ) {
1190 $msg =
"Main file in package must be of type 'script', module " .
1191 "'{$this->getName()}', main file '{$mainFile}' is '{$type}'.";
1192 $this->getLogger()->error( $msg );
1193 throw new LogicException( $msg );
1196 $expandedFiles[$fileName] = $expanded;
1199 if ( $expandedFiles && $mainFile ===
null ) {
1201 foreach ( $expandedFiles as
$path => $file ) {
1202 if ( $file[
'type'] ===
'script' || $file[
'type'] ===
'script-vue' ) {
1210 'main' => $mainFile,
1211 'files' => $expandedFiles
1214 $this->expandedPackageFiles[$hash] = $result;
1247 private function expandFileInfo( Context $context, $fileInfo, $debugKey ) {
1248 if ( is_string( $fileInfo ) ) {
1251 'name' => $fileInfo,
1252 'type' => self::getPackageFileType( $fileInfo ),
1253 'filePath' =>
new FilePath( $fileInfo, $this->localBasePath, $this->remoteBasePath )
1255 } elseif ( $fileInfo instanceof FilePath ) {
1257 'name' => $fileInfo->getPath(),
1260 } elseif ( !is_array( $fileInfo ) ) {
1261 $msg =
"Invalid type in $debugKey for module '{$this->getName()}', " .
1262 "must be array, string or FilePath";
1263 $this->getLogger()->error( $msg );
1264 throw new LogicException( $msg );
1266 if ( !isset( $fileInfo[
'name'] ) ) {
1267 $msg =
"Missing 'name' key in $debugKey for module '{$this->getName()}'";
1268 $this->getLogger()->error( $msg );
1269 throw new LogicException( $msg );
1271 $fileName = $this->getPath( $fileInfo[
'name'] );
1274 $type = $fileInfo[
'type'] ?? self::getPackageFileType( $fileName );
1276 'name' => $fileName,
1279 if ( !empty( $fileInfo[
'main'] ) ) {
1280 $expanded[
'main'] =
true;
1287 if ( isset( $fileInfo[
'content'] ) ) {
1288 $expanded[
'content'] = $fileInfo[
'content'];
1289 } elseif ( isset( $fileInfo[
'file'] ) ) {
1290 $expanded[
'filePath'] = $this->makeFilePath( $fileInfo[
'file'] );
1291 } elseif ( isset( $fileInfo[
'callback'] ) ) {
1293 $expanded[
'callbackParam'] = $fileInfo[
'callbackParam'] ??
null;
1295 if ( !is_callable( $fileInfo[
'callback'] ) ) {
1296 $msg =
"Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
1297 $this->getLogger()->error( $msg );
1298 throw new LogicException( $msg );
1300 if ( isset( $fileInfo[
'versionCallback'] ) ) {
1301 if ( !is_callable( $fileInfo[
'versionCallback'] ) ) {
1302 throw new LogicException(
"Invalid 'versionCallback' for "
1303 .
"module '{$this->getName()}', file '{$fileName}'."
1309 $callbackResult = ( $fileInfo[
'versionCallback'] )(
1312 $expanded[
'callbackParam']
1314 if ( $callbackResult instanceof FilePath ) {
1315 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1316 $expanded[
'versionFilePath'] = $callbackResult;
1318 $expanded[
'definitionSummary'] = $callbackResult;
1321 $expanded[
'callback'] = $fileInfo[
'callback'];
1324 $callbackResult = ( $fileInfo[
'callback'] )(
1327 $expanded[
'callbackParam']
1329 if ( $callbackResult instanceof FilePath ) {
1330 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1331 $expanded[
'filePath'] = $callbackResult;
1333 $expanded[
'content'] = $callbackResult;
1336 } elseif ( isset( $fileInfo[
'config'] ) ) {
1337 if ( $type !==
'data' ) {
1338 $msg =
"Key 'config' only valid for data files. "
1339 .
" Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
1340 $this->getLogger()->error( $msg );
1341 throw new LogicException( $msg );
1343 $expandedConfig = [];
1344 foreach ( $fileInfo[
'config'] as $configKey => $var ) {
1345 $expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
1347 $expanded[
'content'] = $expandedConfig;
1348 } elseif ( !empty( $fileInfo[
'main'] ) ) {
1350 $expanded[
'filePath'] = $this->makeFilePath( $fileName );
1352 $msg =
"Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
1353 .
"One of 'file', 'content', 'callback', or 'config' must be set.";
1354 $this->getLogger()->error( $msg );
1355 throw new LogicException( $msg );
1357 if ( !isset( $expanded[
'filePath'] ) ) {
1358 $expanded[
'virtualFilePath'] = $this->makeFilePath( $fileName );
1369 private function makeFilePath(
$path ): FilePath {
1370 if (
$path instanceof FilePath ) {
1372 } elseif ( is_string(
$path ) ) {
1373 return new FilePath(
$path, $this->localBasePath, $this->remoteBasePath );
1375 throw new InvalidArgumentException(
'$path must be either FilePath or string' );
1386 if ( $this->packageFiles ===
null ) {
1390 if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
1391 return $this->fullyExpandedPackageFiles[ $hash ];
1393 $expandedPackageFiles = $this->expandPackageFiles( $context ) ?? [];
1395 foreach ( $expandedPackageFiles[
'files'] as &$fileInfo ) {
1396 $this->readFileInfo( $context, $fileInfo );
1399 $this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
1400 return $expandedPackageFiles;
1411 private function readFileInfo(
Context $context, array &$fileInfo ) {
1416 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'callback'] ) ) {
1417 $callbackResult = ( $fileInfo[
'callback'] )(
1420 $fileInfo[
'callbackParam']
1422 if ( $callbackResult instanceof
FilePath ) {
1424 $fileInfo[
'filePath'] = $callbackResult;
1426 $fileInfo[
'content'] = $callbackResult;
1428 unset( $fileInfo[
'callback'] );
1435 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'filePath'] ) ) {
1436 $localPath = $this->getLocalPath( $fileInfo[
'filePath'] );
1437 $content = $this->getFileContents( $localPath,
'package' );
1438 if ( $fileInfo[
'type'] ===
'data' ) {
1439 $content = json_decode( $content,
false, 512, JSON_THROW_ON_ERROR );
1441 $fileInfo[
'content'] = $content;
1443 if ( $fileInfo[
'type'] ===
'script-vue' ) {
1445 $parsedComponent = $this->getVueComponentParser()->parse(
1447 $fileInfo[
'content'],
1448 [
'minifyTemplate' => !$context->
getDebug() ]
1450 }
catch ( TimeoutException $e ) {
1452 }
catch ( Exception $e ) {
1453 $msg =
"Error parsing file '{$fileInfo['name']}' in module '{$this->getName()}': " .
1455 $this->getLogger()->error( $msg );
1456 throw new RuntimeException( $msg );
1458 $encodedTemplate = json_encode( $parsedComponent[
'template'] );
1463 $encodedTemplate = preg_replace(
'/(?<!\\\\)\\\\n/',
" \\n\\\n", $encodedTemplate );
1465 $encodedTemplate = strtr( $encodedTemplate, [
"\\t" =>
"\t" ] );
1467 $fileInfo[
'content'] = [
1468 'script' => $parsedComponent[
'script'] .
1469 ";\nmodule.exports.template = $encodedTemplate;",
1470 'style' => $parsedComponent[
'style'] ??
'',
1471 'styleLang' => $parsedComponent[
'styleLang'] ??
'css'
1473 $fileInfo[
'type'] =
'script+style';
1475 if ( !isset( $fileInfo[
'content'] ) ) {
1477 $msg =
"Unable to resolve contents for file {$fileInfo['name']}";
1478 $this->getLogger()->error( $msg );
1479 throw new RuntimeException( $msg );
1483 unset( $fileInfo[
'definitionSummary'] );
1485 unset( $fileInfo[
'callbackParam'] );
1499 if ( str_starts_with( $input,
"\xef\xbb\xbf" ) ) {
1500 return substr( $input, 3 );
if(!defined('MW_SETUP_CALLBACK'))
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 ResourceBasePath
Name constant for the ResourceBasePath setting, for use with Config::get()
This is one of the Core classes and should be read at least once by any new developers.
Context object that contains information about the state of a specific ResourceLoader web request.
getHash()
All factors that uniquely identify this request, except 'modules'.