29use InvalidArgumentException;
37use Wikimedia\Minify\CSSMin;
38use Wikimedia\RequestTimeout\TimeoutException;
103 private $expandedPackageFiles = [];
109 private $fullyExpandedPackageFiles = [];
178 $hasTemplates =
false;
185 foreach ( $options as $member => $option ) {
192 $this->{$member} = is_array( $option ) ? $option : [ $option ];
195 $hasTemplates =
true;
196 $this->{$member} = is_array( $option ) ? $option : [ $option ];
199 case 'languageScripts':
202 if ( !is_array( $option ) ) {
203 throw new InvalidArgumentException(
204 "Invalid collated file path list error. " .
205 "'$option' given, array expected."
208 foreach ( $option as $key => $value ) {
209 if ( !is_string( $key ) ) {
210 throw new InvalidArgumentException(
211 "Invalid collated file path list key error. " .
212 "'$key' given, string expected."
215 $this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
219 $this->deprecated = $option;
225 $option = array_values( array_unique( (array)$option ) );
228 $this->{$member} = $option;
233 $this->{$member} = (string)$option;
238 case 'skipStructureTest':
239 $this->{$member} = (bool)$option;
243 if ( isset( $options[
'scripts'] ) && isset( $options[
'packageFiles'] ) ) {
244 throw new InvalidArgumentException(
"A module may not set both 'scripts' and 'packageFiles'" );
246 if ( isset( $options[
'packageFiles'] ) && isset( $options[
'skinScripts'] ) ) {
247 throw new InvalidArgumentException(
"Options 'skinScripts' and 'packageFiles' cannot be used together." );
249 if ( $hasTemplates ) {
250 $this->dependencies[] =
'mediawiki.template';
252 foreach ( $this->templates as $alias => $templatePath ) {
253 if ( is_int( $alias ) ) {
254 $alias = $this->
getPath( $templatePath );
256 $suffix = explode(
'.', $alias );
257 $suffix = end( $suffix );
258 $compilerModule =
'mediawiki.template.' . $suffix;
259 if ( $suffix !==
'html' && !in_array( $compilerModule, $this->dependencies ) ) {
260 $this->dependencies[] = $compilerModule;
290 if ( isset( $options[
'remoteExtPath'] ) ) {
293 $remoteBasePath = $extensionAssetsPath .
'/' . $options[
'remoteExtPath'];
296 if ( isset( $options[
'remoteSkinPath'] ) ) {
302 if ( array_key_exists(
'localBasePath', $options ) ) {
306 if ( array_key_exists(
'remoteBasePath', $options ) ) {
329 if ( $file[
'type'] ===
'script+style' ) {
330 $file[
'content'] = $file[
'content'][
'script'];
331 $file[
'type'] =
'script';
337 $files = $this->getScriptFiles( $context );
338 foreach ( $files as &$file ) {
339 $this->readFileInfo( $context, $file );
341 return [
'plainScripts' => $files ];
354 foreach ( $this->getScriptFiles( $context ) as $file ) {
355 if ( isset( $file[
'filePath'] ) ) {
358 $url = $rl->expandUrl( $server, $url );
375 && !$this->packageFiles
377 && !$this->hasGeneratedScripts();
381 return $this->skipStructureTest || parent::shouldSkipStructureTest();
389 private function hasGeneratedScripts() {
391 [ $this->scripts, $this->languageScripts, $this->skinScripts, $this->debugScripts ]
395 if ( is_array( $script ) ) {
396 if ( isset( $script[
'callback'] ) || isset( $script[
'versionCallback'] ) ) {
420 if ( $file[
'type'] ===
'script+style' ) {
422 $file[
'content'][
'style'],
423 $file[
'content'][
'styleLang'],
444 if ( $this->hasGeneratedStyles ) {
447 return parent::getStyleURLsForDebug( $context );
452 foreach ( $this->
getStyleFiles( $context ) as $mediaType => $list ) {
453 $urls[$mediaType] = [];
454 foreach ( $list as $file ) {
455 $urls[$mediaType][] = OutputPage::transformResourcePath(
499 private function getFileContents( $localPath, $type ) {
500 if ( !is_file( $localPath ) ) {
501 throw new RuntimeException(
"$type file not found or not a file: \"$localPath\"" );
503 return $this->
stripBom( file_get_contents( $localPath ) );
510 if ( !$this->skipFunction ) {
513 $localPath = $this->
getLocalPath( $this->skipFunction );
514 return $this->getFileContents( $localPath,
'skip function' );
539 private function getFileHashes(
Context $context ) {
543 foreach ( $filePaths as $filePath ) {
551 $expandedPackageFiles = $this->expandPackageFiles( $context );
552 if ( $expandedPackageFiles ) {
553 foreach ( $expandedPackageFiles[
'files'] as $fileInfo ) {
554 if ( isset( $fileInfo[
'filePath'] ) ) {
556 $filePath = $fileInfo[
'filePath'];
557 $files[] = $filePath->getLocalPath();
563 $scriptFileInfos = $this->getScriptFiles( $context );
564 foreach ( $scriptFileInfos as $fileInfo ) {
565 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
566 if ( $filePath instanceof FilePath ) {
567 $files[] = $filePath->getLocalPath();
571 foreach ( $this->templates as $filePath ) {
575 if ( $this->skipFunction ) {
587 $files = array_unique( $files );
603 $summary = parent::getDefinitionSummary( $context );
620 $options[$member] = $this->{$member};
624 $packageSummaries = [];
634 foreach (
$packageFiles[
'files'] as $fileName => $fileInfo ) {
635 $packageSummaries[$fileName] =
636 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
640 $scriptFiles = $this->getScriptFiles( $context );
641 $scriptSummaries = [];
642 foreach ( $scriptFiles as $fileName => $fileInfo ) {
643 $scriptSummaries[$fileName] =
644 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
648 'options' => $options,
649 'packageFiles' => $packageSummaries,
650 'scripts' => $scriptSummaries,
651 'fileHashes' => $this->getFileHashes( $context ),
657 $summary[] = [
'lessVars' => $lessVars ];
667 if ( $this->vueComponentParser ===
null ) {
679 return $path->getPath();
691 if (
$path->getLocalBasePath() !==
null ) {
692 return $path->getLocalPath();
697 return "{$this->localBasePath}/$path";
706 if (
$path->getRemoteBasePath() !==
null ) {
707 return $path->getRemotePath();
712 if ( $this->remoteBasePath ===
'/' ) {
715 return "{$this->remoteBasePath}/$path";
727 return preg_match(
'/\.less$/i',
$path ) ?
'less' :
'css';
737 if ( preg_match(
'/\.json$/i',
$path ) ) {
740 if ( preg_match(
'/\.vue$/i',
$path ) ) {
753 private static function collateStyleFilesByMedia( array $list ) {
755 foreach ( $list as $key => $value ) {
756 if ( is_int( $key ) ) {
758 $collatedFiles[
'all'][] = $value;
759 } elseif ( is_array( $value ) ) {
761 $optionValue = $value[
'media'] ??
'all';
762 $collatedFiles[$optionValue][] = $key;
765 return $collatedFiles;
778 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
795 private function getScriptFiles(
Context $context ): array {
799 'scripts' => $this->scripts,
800 'languageScripts' => $this->getLanguageScripts( $context->getLanguage() ),
801 'skinScripts' => self::
tryForKey( $this->skinScripts, $context->getSkin(),
'default' ),
808 foreach ( $filesByCategory as $category => $files ) {
809 foreach ( $files as $key => $fileInfo ) {
810 $expandedFileInfo = $this->expandFileInfo( $context, $fileInfo,
"$category\[$key]" );
811 $expandedFiles[$expandedFileInfo[
'name']] = $expandedFileInfo;
815 return $expandedFiles;
825 private function getLanguageScripts(
string $lang ): array {
826 $scripts = self::tryForKey( $this->languageScripts, $lang );
833 if ( $this->languageScripts ) {
835 ->getLanguageFallback()
836 ->getAll( $lang, LanguageFallback::MESSAGES );
837 foreach ( $fallbacks as $lang ) {
838 $scripts = self::tryForKey( $this->languageScripts, $lang );
849 $moduleName = $this->getName();
850 foreach ( $moduleSkinStyles as $skinName => $overrides ) {
853 if ( isset( $this->skinStyles[$skinName] ) ) {
859 if ( isset( $overrides[$moduleName] ) ) {
860 $paths = (array)$overrides[$moduleName];
862 } elseif ( isset( $overrides[
'+' . $moduleName] ) ) {
863 $paths = (array)$overrides[
'+' . $moduleName];
864 $styleFiles = isset( $this->skinStyles[
'default'] ) ?
865 (array)$this->skinStyles[
'default'] :
873 [ $localBasePath, $remoteBasePath ] = self::extractBasePaths( $overrides );
875 foreach ( $paths as
$path ) {
876 $styleFiles[] =
new FilePath(
$path, $localBasePath, $remoteBasePath );
879 $this->skinStyles[$skinName] = $styleFiles;
891 return array_merge_recursive(
892 self::collateStyleFilesByMedia( $this->styles ),
893 self::collateStyleFilesByMedia(
894 self::tryForKey( $this->skinStyles, $context->
getSkin(),
'default' )
907 return self::collateStyleFilesByMedia(
908 self::tryForKey( $this->skinStyles, $skinName )
919 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
922 $internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
923 $internalSkinNames[] =
'default';
925 foreach ( $internalSkinNames as $internalSkinName ) {
926 $styleFiles = array_merge_recursive(
928 $this->getSkinStyleFiles( $internalSkinName )
941 $collatedStyleFiles = array_merge_recursive(
942 self::collateStyleFilesByMedia( $this->styles ),
943 $this->getAllSkinStyleFiles()
948 foreach ( $collatedStyleFiles as $styleFiles ) {
949 foreach ( $styleFiles as $styleFile ) {
950 $result[] = $this->getLocalPath( $styleFile );
969 foreach ( $styles as $media => $files ) {
970 $uniqueFiles = array_unique( $files, SORT_REGULAR );
972 foreach ( $uniqueFiles as $file ) {
973 $styleFiles[] = $this->readStyleFile( $file, $context );
975 $styles[$media] = implode(
"\n", $styleFiles );
991 $localPath = $this->getLocalPath(
$path );
992 $style = $this->getFileContents( $localPath,
'style' );
993 $styleLang = $this->getStyleSheetLang( $localPath );
995 return $this->processStyle( $style, $styleLang,
$path, $context );
1015 $localPath = $this->getLocalPath(
$path );
1016 $remotePath = $this->getRemotePath(
$path );
1018 if ( $styleLang ===
'less' ) {
1019 $style = $this->compileLessString( $style, $localPath, $context );
1020 $this->hasGeneratedStyles =
true;
1023 if ( $this->getFlip( $context ) ) {
1024 $style = CSSJanus::transform(
1031 $localDir = dirname( $localPath );
1032 $remoteDir = dirname( $remotePath );
1034 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
1035 foreach ( $localFileRefs as $file ) {
1036 if ( is_file( $file ) ) {
1037 $this->localFileRefs[] = $file;
1039 $this->missingLocalFileRefs[] = $file;
1044 return CSSMin::remap( $style, $localDir, $remoteDir,
true );
1053 return $context->
getDirection() ===
'rtl' && !$this->noflip;
1063 $canBeStylesOnly = !(
1066 || $this->debugScripts
1068 || $this->languageScripts
1069 || $this->skinScripts
1070 || $this->dependencies
1072 || $this->skipFunction
1073 || $this->packageFiles
1075 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
1096 $skinName = $context->
getSkin();
1097 $skinImportPaths = ExtensionRegistry::getInstance()->getAttribute(
'SkinLessImportPaths' );
1099 if ( isset( $skinImportPaths[ $skinName ] ) ) {
1100 $importDirs[] = $skinImportPaths[ $skinName ];
1103 $vars = $this->getLessVars( $context );
1109 'importDirs' => $importDirs,
1111 $key = $cache->makeGlobalKey(
1112 'resourceloader-less',
1114 hash(
'md4', $style ),
1115 hash(
'md4', serialize( $compilerParams ) )
1120 $data = $cache->get( $key );
1123 $data[
'hash'] !== FileContentsHasher::getFileContentsHash( $data[
'files'] )
1125 $compiler = $context->
getResourceLoader()->getLessCompiler( $vars, $importDirs );
1127 $css = $compiler->parse( $style, $stylePath )->getCss();
1131 $files = $compiler->AllParsedFiles();
1134 'files' => Module::getRelativePaths( $files ),
1135 'hash' => FileContentsHasher::getFileContentsHash( $files )
1137 $cache->set( $key, $data, $cache::TTL_DAY );
1140 foreach ( Module::expandRelativePaths( $data[
'files'] ) as
$path ) {
1141 $this->localFileRefs[] =
$path;
1144 return $data[
'css'];
1155 foreach ( $this->templates as $alias => $templatePath ) {
1157 if ( is_int( $alias ) ) {
1158 $alias = $this->getPath( $templatePath );
1160 $localPath = $this->getLocalPath( $templatePath );
1161 $content = $this->getFileContents( $localPath,
'template' );
1163 $templates[$alias] = $this->stripBom( $content );
1187 private function expandPackageFiles(
Context $context ) {
1189 if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1190 return $this->expandedPackageFiles[$hash];
1192 if ( $this->packageFiles ===
null ) {
1195 $expandedFiles = [];
1198 foreach ( $this->packageFiles as $key => $fileInfo ) {
1199 $expanded = $this->expandFileInfo( $context, $fileInfo,
"packageFiles[$key]" );
1200 $fileName = $expanded[
'name'];
1201 if ( !empty( $expanded[
'main'] ) ) {
1202 unset( $expanded[
'main'] );
1203 $type = $expanded[
'type'];
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 );
1212 $expandedFiles[$fileName] = $expanded;
1215 if ( $expandedFiles && $mainFile ===
null ) {
1217 foreach ( $expandedFiles as
$path => $file ) {
1218 if ( $file[
'type'] ===
'script' || $file[
'type'] ===
'script-vue' ) {
1226 'main' => $mainFile,
1227 'files' => $expandedFiles
1230 $this->expandedPackageFiles[$hash] = $result;
1263 private function expandFileInfo( Context $context, $fileInfo, $debugKey ) {
1264 if ( is_string( $fileInfo ) ) {
1267 'name' => $fileInfo,
1268 'type' => self::getPackageFileType( $fileInfo ),
1269 'filePath' =>
new FilePath( $fileInfo, $this->localBasePath, $this->remoteBasePath )
1271 } elseif ( $fileInfo instanceof FilePath ) {
1273 'name' => $fileInfo->getPath(),
1276 } elseif ( !is_array( $fileInfo ) ) {
1277 $msg =
"Invalid type in $debugKey for module '{$this->getName()}', " .
1278 "must be array, string or FilePath";
1279 $this->getLogger()->error( $msg );
1280 throw new LogicException( $msg );
1282 if ( !isset( $fileInfo[
'name'] ) ) {
1283 $msg =
"Missing 'name' key in $debugKey for module '{$this->getName()}'";
1284 $this->getLogger()->error( $msg );
1285 throw new LogicException( $msg );
1287 $fileName = $this->getPath( $fileInfo[
'name'] );
1290 $type = $fileInfo[
'type'] ?? self::getPackageFileType( $fileName );
1292 'name' => $fileName,
1295 if ( !empty( $fileInfo[
'main'] ) ) {
1296 $expanded[
'main'] =
true;
1303 if ( isset( $fileInfo[
'content'] ) ) {
1304 $expanded[
'content'] = $fileInfo[
'content'];
1305 } elseif ( isset( $fileInfo[
'file'] ) ) {
1306 $expanded[
'filePath'] = $this->makeFilePath( $fileInfo[
'file'] );
1307 } elseif ( isset( $fileInfo[
'callback'] ) ) {
1309 $expanded[
'callbackParam'] = $fileInfo[
'callbackParam'] ??
null;
1311 if ( !is_callable( $fileInfo[
'callback'] ) ) {
1312 $msg =
"Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
1313 $this->getLogger()->error( $msg );
1314 throw new LogicException( $msg );
1316 if ( isset( $fileInfo[
'versionCallback'] ) ) {
1317 if ( !is_callable( $fileInfo[
'versionCallback'] ) ) {
1318 throw new LogicException(
"Invalid 'versionCallback' for "
1319 .
"module '{$this->getName()}', file '{$fileName}'."
1325 $callbackResult = ( $fileInfo[
'versionCallback'] )(
1328 $expanded[
'callbackParam']
1330 if ( $callbackResult instanceof FilePath ) {
1331 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1332 $expanded[
'versionFilePath'] = $callbackResult;
1334 $expanded[
'definitionSummary'] = $callbackResult;
1337 $expanded[
'callback'] = $fileInfo[
'callback'];
1340 $callbackResult = ( $fileInfo[
'callback'] )(
1343 $expanded[
'callbackParam']
1345 if ( $callbackResult instanceof FilePath ) {
1346 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1347 $expanded[
'filePath'] = $callbackResult;
1349 $expanded[
'content'] = $callbackResult;
1352 } elseif ( isset( $fileInfo[
'config'] ) ) {
1353 if ( $type !==
'data' ) {
1354 $msg =
"Key 'config' only valid for data files. "
1355 .
" Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
1356 $this->getLogger()->error( $msg );
1357 throw new LogicException( $msg );
1359 $expandedConfig = [];
1360 foreach ( $fileInfo[
'config'] as $configKey => $var ) {
1361 $expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
1363 $expanded[
'content'] = $expandedConfig;
1364 } elseif ( !empty( $fileInfo[
'main'] ) ) {
1366 $expanded[
'filePath'] = $this->makeFilePath( $fileName );
1368 $msg =
"Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
1369 .
"One of 'file', 'content', 'callback', or 'config' must be set.";
1370 $this->getLogger()->error( $msg );
1371 throw new LogicException( $msg );
1373 if ( !isset( $expanded[
'filePath'] ) ) {
1374 $expanded[
'virtualFilePath'] = $this->makeFilePath( $fileName );
1385 private function makeFilePath(
$path ): FilePath {
1386 if (
$path instanceof FilePath ) {
1388 } elseif ( is_string(
$path ) ) {
1389 return new FilePath(
$path, $this->localBasePath, $this->remoteBasePath );
1391 throw new InvalidArgumentException(
'$path must be either FilePath or string' );
1402 if ( $this->packageFiles ===
null ) {
1406 if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
1407 return $this->fullyExpandedPackageFiles[ $hash ];
1409 $expandedPackageFiles = $this->expandPackageFiles( $context ) ?? [];
1411 foreach ( $expandedPackageFiles[
'files'] as &$fileInfo ) {
1412 $this->readFileInfo( $context, $fileInfo );
1415 $this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
1416 return $expandedPackageFiles;
1427 private function readFileInfo(
Context $context, array &$fileInfo ) {
1432 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'callback'] ) ) {
1433 $callbackResult = ( $fileInfo[
'callback'] )(
1436 $fileInfo[
'callbackParam']
1438 if ( $callbackResult instanceof
FilePath ) {
1440 $fileInfo[
'filePath'] = $callbackResult;
1442 $fileInfo[
'content'] = $callbackResult;
1444 unset( $fileInfo[
'callback'] );
1451 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'filePath'] ) ) {
1452 $localPath = $this->getLocalPath( $fileInfo[
'filePath'] );
1453 $content = $this->getFileContents( $localPath,
'package' );
1454 if ( $fileInfo[
'type'] ===
'data' ) {
1455 $content = json_decode( $content,
false, 512, JSON_THROW_ON_ERROR );
1457 $fileInfo[
'content'] = $content;
1459 if ( $fileInfo[
'type'] ===
'script-vue' ) {
1461 $parsedComponent = $this->getVueComponentParser()->parse(
1463 $fileInfo[
'content'],
1464 [
'minifyTemplate' => !$context->
getDebug() ]
1466 }
catch ( TimeoutException $e ) {
1468 }
catch ( Exception $e ) {
1469 $msg =
"Error parsing file '{$fileInfo['name']}' in module '{$this->getName()}': " .
1471 $this->getLogger()->error( $msg );
1472 throw new RuntimeException( $msg );
1474 $encodedTemplate = json_encode( $parsedComponent[
'template'] );
1479 $encodedTemplate = preg_replace(
'/(?<!\\\\)\\\\n/',
" \\n\\\n", $encodedTemplate );
1481 $encodedTemplate = strtr( $encodedTemplate, [
"\\t" =>
"\t" ] );
1483 $fileInfo[
'content'] = [
1484 'script' => $parsedComponent[
'script'] .
1485 ";\nmodule.exports.template = $encodedTemplate;",
1486 'style' => $parsedComponent[
'style'] ??
'',
1487 'styleLang' => $parsedComponent[
'styleLang'] ??
'css'
1489 $fileInfo[
'type'] =
'script+style';
1491 if ( !isset( $fileInfo[
'content'] ) ) {
1493 $msg =
"Unable to resolve contents for file {$fileInfo['name']}";
1494 $this->getLogger()->error( $msg );
1495 throw new RuntimeException( $msg );
1499 unset( $fileInfo[
'definitionSummary'] );
1501 unset( $fileInfo[
'callbackParam'] );
1515 if ( str_starts_with( $input,
"\xef\xbb\xbf" ) ) {
1516 return substr( $input, 3 );
if(!defined('MW_SETUP_CALLBACK'))
Load JSON files, and uses a Processor to extract information.
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()
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'.