28use InvalidArgumentException;
30use MediaWiki\Languages\LanguageFallback;
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 ) ) {
331 if ( $file[
'type'] ===
'script+style' ) {
332 $file[
'content'] = $file[
'content'][
'script'];
333 $file[
'type'] =
'script';
339 $files = $this->getScriptFiles( $context );
340 foreach ( $files as &$file ) {
341 $this->readFileInfo( $context, $file );
343 return [
'plainScripts' => $files ];
356 && !$this->packageFiles
358 && !$this->hasGeneratedScripts();
363 return $this->skipStructureTest || parent::shouldSkipStructureTest();
371 private function hasGeneratedScripts() {
373 [ $this->scripts, $this->languageScripts, $this->skinScripts, $this->debugScripts ]
377 if ( is_array( $script ) ) {
378 if ( isset( $script[
'callback'] ) || isset( $script[
'versionCallback'] ) ) {
402 if ( $file[
'type'] ===
'script+style' ) {
404 $file[
'content'][
'style'],
405 $file[
'content'][
'styleLang'],
426 if ( $this->hasGeneratedStyles ) {
429 return parent::getStyleURLsForDebug( $context );
434 foreach ( $this->
getStyleFiles( $context ) as $mediaType => $list ) {
435 $urls[$mediaType] = [];
436 foreach ( $list as $file ) {
437 $urls[$mediaType][] = OutputPage::transformResourcePath(
481 private function getFileContents( $localPath, $type ) {
482 if ( !is_file( $localPath ) ) {
483 throw new RuntimeException(
"$type file not found or not a file: \"$localPath\"" );
485 return $this->
stripBom( file_get_contents( $localPath ) );
492 if ( !$this->skipFunction ) {
495 $localPath = $this->
getLocalPath( $this->skipFunction );
496 return $this->getFileContents( $localPath,
'skip function' );
522 private function getFileHashes(
Context $context ) {
526 foreach ( $filePaths as $filePath ) {
534 $expandedPackageFiles = $this->expandPackageFiles( $context );
535 if ( $expandedPackageFiles ) {
536 foreach ( $expandedPackageFiles[
'files'] as $fileInfo ) {
537 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
538 if ( $filePath instanceof FilePath ) {
539 $files[] = $filePath->getLocalPath();
545 $scriptFileInfos = $this->getScriptFiles( $context );
546 foreach ( $scriptFileInfos as $fileInfo ) {
547 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
548 if ( $filePath instanceof FilePath ) {
549 $files[] = $filePath->getLocalPath();
553 foreach ( $this->templates as $filePath ) {
557 if ( $this->skipFunction ) {
569 $files = array_unique( $files );
585 $summary = parent::getDefinitionSummary( $context );
602 $options[$member] = $this->{$member};
606 $packageSummaries = [];
616 foreach (
$packageFiles[
'files'] as $fileName => $fileInfo ) {
617 $packageSummaries[$fileName] =
618 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
622 $scriptFiles = $this->getScriptFiles( $context );
623 $scriptSummaries = [];
624 foreach ( $scriptFiles as $fileName => $fileInfo ) {
625 $scriptSummaries[$fileName] =
626 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
630 'options' => $options,
631 'packageFiles' => $packageSummaries,
632 'scripts' => $scriptSummaries,
633 'fileHashes' => $this->getFileHashes( $context ),
639 $summary[] = [
'lessVars' => $lessVars ];
649 if ( $this->vueComponentParser ===
null ) {
661 return $path->getPath();
673 if (
$path->getLocalBasePath() !==
null ) {
674 return $path->getLocalPath();
679 return "{$this->localBasePath}/$path";
688 if (
$path->getRemoteBasePath() !==
null ) {
689 return $path->getRemotePath();
694 if ( $this->remoteBasePath ===
'/' ) {
697 return "{$this->remoteBasePath}/$path";
709 return preg_match(
'/\.less$/i',
$path ) ?
'less' :
'css';
719 if ( preg_match(
'/\.json$/i',
$path ) ) {
722 if ( preg_match(
'/\.vue$/i',
$path ) ) {
735 private static function collateStyleFilesByMedia( array $list ) {
737 foreach ( $list as $key => $value ) {
738 if ( is_int( $key ) ) {
740 $collatedFiles[
'all'][] = $value;
741 } elseif ( is_array( $value ) ) {
743 $optionValue = $value[
'media'] ??
'all';
744 $collatedFiles[$optionValue][] = $key;
747 return $collatedFiles;
760 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
777 private function getScriptFiles(
Context $context ): array {
781 'scripts' => $this->scripts,
782 'languageScripts' => $this->getLanguageScripts( $context->getLanguage() ),
783 'skinScripts' => self::
tryForKey( $this->skinScripts, $context->getSkin(),
'default' ),
790 foreach ( $filesByCategory as $category => $files ) {
791 foreach ( $files as $key => $fileInfo ) {
792 $expandedFileInfo = $this->expandFileInfo( $context, $fileInfo,
"$category\[$key]" );
793 $expandedFiles[$expandedFileInfo[
'name']] = $expandedFileInfo;
797 return $expandedFiles;
807 private function getLanguageScripts(
string $lang ): array {
808 $scripts = self::tryForKey( $this->languageScripts, $lang );
815 if ( $this->languageScripts ) {
817 ->getLanguageFallback()
818 ->getAll( $lang, LanguageFallback::MESSAGES );
819 foreach ( $fallbacks as $lang ) {
820 $scripts = self::tryForKey( $this->languageScripts, $lang );
831 $moduleName = $this->getName();
832 foreach ( $moduleSkinStyles as $skinName => $overrides ) {
835 if ( isset( $this->skinStyles[$skinName] ) ) {
841 if ( isset( $overrides[$moduleName] ) ) {
842 $paths = (array)$overrides[$moduleName];
844 } elseif ( isset( $overrides[
'+' . $moduleName] ) ) {
845 $paths = (array)$overrides[
'+' . $moduleName];
846 $styleFiles = isset( $this->skinStyles[
'default'] ) ?
847 (array)$this->skinStyles[
'default'] :
855 [ $localBasePath, $remoteBasePath ] = self::extractBasePaths( $overrides );
857 foreach ( $paths as
$path ) {
858 $styleFiles[] =
new FilePath(
$path, $localBasePath, $remoteBasePath );
861 $this->skinStyles[$skinName] = $styleFiles;
873 return array_merge_recursive(
874 self::collateStyleFilesByMedia( $this->styles ),
875 self::collateStyleFilesByMedia(
876 self::tryForKey( $this->skinStyles, $context->
getSkin(),
'default' )
889 return self::collateStyleFilesByMedia(
890 self::tryForKey( $this->skinStyles, $skinName )
901 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
904 $internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
905 $internalSkinNames[] =
'default';
907 foreach ( $internalSkinNames as $internalSkinName ) {
908 $styleFiles = array_merge_recursive(
910 $this->getSkinStyleFiles( $internalSkinName )
923 $collatedStyleFiles = array_merge_recursive(
924 self::collateStyleFilesByMedia( $this->styles ),
925 $this->getAllSkinStyleFiles()
930 foreach ( $collatedStyleFiles as $styleFiles ) {
931 foreach ( $styleFiles as $styleFile ) {
932 $result[] = $this->getLocalPath( $styleFile );
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(
1011 $this->hasGeneratedStyles =
true;
1014 $localDir = dirname( $localPath );
1015 $remoteDir = dirname( $remotePath );
1017 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
1018 foreach ( $localFileRefs as $file ) {
1019 if ( is_file( $file ) ) {
1020 $this->localFileRefs[] = $file;
1022 $this->missingLocalFileRefs[] = $file;
1027 return CSSMin::remap( $style, $localDir, $remoteDir,
true );
1036 return $context->
getDirection() ===
'rtl' && !$this->noflip;
1046 $canBeStylesOnly = !(
1049 || $this->debugScripts
1051 || $this->languageScripts
1052 || $this->skinScripts
1053 || $this->dependencies
1055 || $this->skipFunction
1056 || $this->packageFiles
1058 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
1076 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()
1080 $skinName = $context->
getSkin();
1081 $skinImportPaths = ExtensionRegistry::getInstance()->getAttribute(
'SkinLessImportPaths' );
1083 if ( isset( $skinImportPaths[ $skinName ] ) ) {
1084 $importDirs[] = $skinImportPaths[ $skinName ];
1087 $vars = $this->getLessVars( $context );
1093 'importDirs' => $importDirs,
1096 'codexDevDir' => $this->getConfig()->get( MainConfigNames::CodexDevelopmentDir )
1098 $key = $cache->makeGlobalKey(
1099 'resourceloader-less',
1101 hash(
'md4', $style ),
1102 hash(
'md4', serialize( $compilerParams ) )
1107 $data = $cache->get( $key );
1110 $data[
'hash'] !== FileContentsHasher::getFileContentsHash( $data[
'files'] )
1112 $compiler = $context->
getResourceLoader()->getLessCompiler( $vars, $importDirs );
1114 $css = $compiler->parse( $style, $stylePath )->getCss();
1118 $files = $compiler->getParsedFiles();
1121 'files' => Module::getRelativePaths( $files ),
1122 'hash' => FileContentsHasher::getFileContentsHash( $files )
1124 $cache->set( $key, $data, $cache::TTL_DAY );
1127 foreach ( Module::expandRelativePaths( $data[
'files'] ) as
$path ) {
1128 $this->localFileRefs[] =
$path;
1131 return $data[
'css'];
1142 foreach ( $this->templates as $alias => $templatePath ) {
1144 if ( is_int( $alias ) ) {
1145 $alias = $this->getPath( $templatePath );
1147 $localPath = $this->getLocalPath( $templatePath );
1148 $content = $this->getFileContents( $localPath,
'template' );
1150 $templates[$alias] = $this->stripBom( $content );
1174 private function expandPackageFiles(
Context $context ) {
1176 if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1177 return $this->expandedPackageFiles[$hash];
1179 if ( $this->packageFiles ===
null ) {
1182 $expandedFiles = [];
1185 foreach ( $this->packageFiles as $key => $fileInfo ) {
1186 $expanded = $this->expandFileInfo( $context, $fileInfo,
"packageFiles[$key]" );
1187 $fileName = $expanded[
'name'];
1188 if ( !empty( $expanded[
'main'] ) ) {
1189 unset( $expanded[
'main'] );
1190 $type = $expanded[
'type'];
1191 $mainFile = $fileName;
1192 if ( $type !==
'script' && $type !==
'script-vue' ) {
1193 $msg =
"Main file in package must be of type 'script', module " .
1194 "'{$this->getName()}', main file '{$mainFile}' is '{$type}'.";
1195 $this->getLogger()->error( $msg );
1196 throw new LogicException( $msg );
1199 $expandedFiles[$fileName] = $expanded;
1202 if ( $expandedFiles && $mainFile ===
null ) {
1204 foreach ( $expandedFiles as
$path => $file ) {
1205 if ( $file[
'type'] ===
'script' || $file[
'type'] ===
'script-vue' ) {
1213 'main' => $mainFile,
1214 'files' => $expandedFiles
1217 $this->expandedPackageFiles[$hash] = $result;
1250 private function expandFileInfo( Context $context, $fileInfo, $debugKey ) {
1251 if ( is_string( $fileInfo ) ) {
1254 'name' => $fileInfo,
1255 'type' => self::getPackageFileType( $fileInfo ),
1256 'filePath' =>
new FilePath( $fileInfo, $this->localBasePath, $this->remoteBasePath )
1258 } elseif ( $fileInfo instanceof FilePath ) {
1260 'name' => $fileInfo->getPath(),
1263 } elseif ( !is_array( $fileInfo ) ) {
1264 $msg =
"Invalid type in $debugKey for module '{$this->getName()}', " .
1265 "must be array, string or FilePath";
1266 $this->getLogger()->error( $msg );
1267 throw new LogicException( $msg );
1269 if ( !isset( $fileInfo[
'name'] ) ) {
1270 $msg =
"Missing 'name' key in $debugKey for module '{$this->getName()}'";
1271 $this->getLogger()->error( $msg );
1272 throw new LogicException( $msg );
1274 $fileName = $this->getPath( $fileInfo[
'name'] );
1277 $type = $fileInfo[
'type'] ?? self::getPackageFileType( $fileName );
1279 'name' => $fileName,
1282 if ( !empty( $fileInfo[
'main'] ) ) {
1283 $expanded[
'main'] =
true;
1290 if ( isset( $fileInfo[
'content'] ) ) {
1291 $expanded[
'content'] = $fileInfo[
'content'];
1292 } elseif ( isset( $fileInfo[
'file'] ) ) {
1293 $expanded[
'filePath'] = $this->makeFilePath( $fileInfo[
'file'] );
1294 } elseif ( isset( $fileInfo[
'callback'] ) ) {
1296 $expanded[
'callbackParam'] = $fileInfo[
'callbackParam'] ??
null;
1298 if ( !is_callable( $fileInfo[
'callback'] ) ) {
1299 $msg =
"Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
1300 $this->getLogger()->error( $msg );
1301 throw new LogicException( $msg );
1303 if ( isset( $fileInfo[
'versionCallback'] ) ) {
1304 if ( !is_callable( $fileInfo[
'versionCallback'] ) ) {
1305 throw new LogicException(
"Invalid 'versionCallback' for "
1306 .
"module '{$this->getName()}', file '{$fileName}'."
1312 $callbackResult = ( $fileInfo[
'versionCallback'] )(
1315 $expanded[
'callbackParam']
1317 if ( $callbackResult instanceof FilePath ) {
1318 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1319 $expanded[
'versionFilePath'] = $callbackResult;
1321 $expanded[
'definitionSummary'] = $callbackResult;
1324 $expanded[
'callback'] = $fileInfo[
'callback'];
1327 $callbackResult = ( $fileInfo[
'callback'] )(
1330 $expanded[
'callbackParam']
1332 if ( $callbackResult instanceof FilePath ) {
1333 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1334 $expanded[
'filePath'] = $callbackResult;
1336 $expanded[
'content'] = $callbackResult;
1339 } elseif ( isset( $fileInfo[
'config'] ) ) {
1340 if ( $type !==
'data' ) {
1341 $msg =
"Key 'config' only valid for data files. "
1342 .
" Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
1343 $this->getLogger()->error( $msg );
1344 throw new LogicException( $msg );
1346 $expandedConfig = [];
1347 foreach ( $fileInfo[
'config'] as $configKey => $var ) {
1348 $expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
1350 $expanded[
'content'] = $expandedConfig;
1351 } elseif ( !empty( $fileInfo[
'main'] ) ) {
1353 $expanded[
'filePath'] = $this->makeFilePath( $fileName );
1355 $msg =
"Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
1356 .
"One of 'file', 'content', 'callback', or 'config' must be set.";
1357 $this->getLogger()->error( $msg );
1358 throw new LogicException( $msg );
1360 if ( !isset( $expanded[
'filePath'] ) ) {
1361 $expanded[
'virtualFilePath'] = $this->makeFilePath( $fileName );
1372 private function makeFilePath(
$path ): FilePath {
1373 if (
$path instanceof FilePath ) {
1375 } elseif ( is_string(
$path ) ) {
1376 return new FilePath(
$path, $this->localBasePath, $this->remoteBasePath );
1378 throw new InvalidArgumentException(
'$path must be either FilePath or string' );
1389 if ( $this->packageFiles ===
null ) {
1393 if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
1394 return $this->fullyExpandedPackageFiles[ $hash ];
1396 $expandedPackageFiles = $this->expandPackageFiles( $context ) ?? [];
1398 foreach ( $expandedPackageFiles[
'files'] as &$fileInfo ) {
1399 $this->readFileInfo( $context, $fileInfo );
1402 $this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
1403 return $expandedPackageFiles;
1414 private function readFileInfo(
Context $context, array &$fileInfo ) {
1419 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'callback'] ) ) {
1420 $callbackResult = ( $fileInfo[
'callback'] )(
1423 $fileInfo[
'callbackParam']
1425 if ( $callbackResult instanceof
FilePath ) {
1427 $fileInfo[
'filePath'] = $callbackResult;
1429 $fileInfo[
'content'] = $callbackResult;
1431 unset( $fileInfo[
'callback'] );
1438 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'filePath'] ) ) {
1439 $localPath = $this->getLocalPath( $fileInfo[
'filePath'] );
1440 $content = $this->getFileContents( $localPath,
'package' );
1441 if ( $fileInfo[
'type'] ===
'data' ) {
1442 $content = json_decode( $content,
false, 512, JSON_THROW_ON_ERROR );
1444 $fileInfo[
'content'] = $content;
1446 if ( $fileInfo[
'type'] ===
'script-vue' ) {
1448 $parsedComponent = $this->getVueComponentParser()->parse(
1450 $fileInfo[
'content'],
1451 [
'minifyTemplate' => !$context->
getDebug() ]
1453 }
catch ( TimeoutException $e ) {
1455 }
catch ( Exception $e ) {
1456 $msg =
"Error parsing file '{$fileInfo['name']}' in module '{$this->getName()}': " .
1458 $this->getLogger()->error( $msg );
1459 throw new RuntimeException( $msg );
1461 $encodedTemplate = json_encode( $parsedComponent[
'template'] );
1466 $encodedTemplate = preg_replace(
'/(?<!\\\\)\\\\n/',
" \\n\\\n", $encodedTemplate );
1468 $encodedTemplate = strtr( $encodedTemplate, [
"\\t" =>
"\t" ] );
1470 $fileInfo[
'content'] = [
1471 'script' => $parsedComponent[
'script'] .
1472 ";\nmodule.exports.template = $encodedTemplate;",
1473 'style' => $parsedComponent[
'style'] ??
'',
1474 'styleLang' => $parsedComponent[
'styleLang'] ??
'css'
1476 $fileInfo[
'type'] =
'script+style';
1478 if ( !isset( $fileInfo[
'content'] ) ) {
1480 $msg =
"Unable to resolve contents for file {$fileInfo['name']}";
1481 $this->getLogger()->error( $msg );
1482 throw new RuntimeException( $msg );
1486 unset( $fileInfo[
'definitionSummary'] );
1488 unset( $fileInfo[
'callbackParam'] );
1502 if ( str_starts_with( $input,
"\xef\xbb\xbf" ) ) {
1503 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'.