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 ) ) {
326 if ( $file[
'type'] ===
'script+style' ) {
327 $file[
'content'] = $file[
'content'][
'script'];
328 $file[
'type'] =
'script';
334 $files = $this->getScriptFiles( $context );
335 foreach ( $files as &$file ) {
336 $this->readFileInfo( $context, $file );
338 return [
'plainScripts' => $files ];
351 foreach ( $this->getScriptFiles( $context ) as $file ) {
352 if ( isset( $file[
'filePath'] ) ) {
355 $url = $rl->expandUrl( $server,
$url );
372 && !$this->packageFiles
374 && !$this->hasGeneratedScripts();
378 return $this->skipStructureTest || parent::shouldSkipStructureTest();
386 private function hasGeneratedScripts() {
388 [ $this->scripts, $this->languageScripts, $this->skinScripts, $this->debugScripts ]
392 if ( is_array( $script ) ) {
393 if ( isset( $script[
'callback'] ) || isset( $script[
'versionCallback'] ) ) {
417 if ( $file[
'type'] ===
'script+style' ) {
419 $file[
'content'][
'style'],
420 $file[
'content'][
'styleLang'],
441 if ( $this->hasGeneratedStyles ) {
444 return parent::getStyleURLsForDebug( $context );
449 foreach ( $this->
getStyleFiles( $context ) as $mediaType => $list ) {
450 $urls[$mediaType] = [];
451 foreach ( $list as $file ) {
452 $urls[$mediaType][] = OutputPage::transformResourcePath(
496 private function getFileContents( $localPath, $type ) {
497 if ( !is_file( $localPath ) ) {
498 throw new RuntimeException(
"$type file not found or not a file: \"$localPath\"" );
500 return $this->
stripBom( file_get_contents( $localPath ) );
507 if ( !$this->skipFunction ) {
510 $localPath = $this->
getLocalPath( $this->skipFunction );
511 return $this->getFileContents( $localPath,
'skip function' );
536 private function getFileHashes(
Context $context ) {
540 foreach ( $filePaths as $filePath ) {
548 $expandedPackageFiles = $this->expandPackageFiles( $context );
549 if ( $expandedPackageFiles ) {
550 foreach ( $expandedPackageFiles[
'files'] as $fileInfo ) {
551 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
552 if ( $filePath instanceof FilePath ) {
553 $files[] = $filePath->getLocalPath();
559 $scriptFileInfos = $this->getScriptFiles( $context );
560 foreach ( $scriptFileInfos as $fileInfo ) {
561 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
562 if ( $filePath instanceof FilePath ) {
563 $files[] = $filePath->getLocalPath();
567 foreach ( $this->templates as $filePath ) {
571 if ( $this->skipFunction ) {
583 $files = array_unique( $files );
599 $summary = parent::getDefinitionSummary( $context );
616 $options[$member] = $this->{$member};
620 $packageSummaries = [];
630 foreach (
$packageFiles[
'files'] as $fileName => $fileInfo ) {
631 $packageSummaries[$fileName] =
632 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
636 $scriptFiles = $this->getScriptFiles( $context );
637 $scriptSummaries = [];
638 foreach ( $scriptFiles as $fileName => $fileInfo ) {
639 $scriptSummaries[$fileName] =
640 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
644 'options' => $options,
645 'packageFiles' => $packageSummaries,
646 'scripts' => $scriptSummaries,
647 'fileHashes' => $this->getFileHashes( $context ),
653 $summary[] = [
'lessVars' => $lessVars ];
663 if ( $this->vueComponentParser ===
null ) {
675 return $path->getPath();
687 if (
$path->getLocalBasePath() !==
null ) {
688 return $path->getLocalPath();
693 return "{$this->localBasePath}/$path";
702 if (
$path->getRemoteBasePath() !==
null ) {
703 return $path->getRemotePath();
708 if ( $this->remoteBasePath ===
'/' ) {
711 return "{$this->remoteBasePath}/$path";
723 return preg_match(
'/\.less$/i',
$path ) ?
'less' :
'css';
733 if ( preg_match(
'/\.json$/i',
$path ) ) {
736 if ( preg_match(
'/\.vue$/i',
$path ) ) {
749 private static function collateStyleFilesByMedia( array $list ) {
751 foreach ( $list as $key => $value ) {
752 if ( is_int( $key ) ) {
754 $collatedFiles[
'all'][] = $value;
755 } elseif ( is_array( $value ) ) {
757 $optionValue = $value[
'media'] ??
'all';
758 $collatedFiles[$optionValue][] = $key;
761 return $collatedFiles;
774 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
791 private function getScriptFiles(
Context $context ): array {
795 'scripts' => $this->scripts,
796 'languageScripts' => $this->getLanguageScripts( $context->getLanguage() ),
797 'skinScripts' => self::
tryForKey( $this->skinScripts, $context->getSkin(),
'default' ),
804 foreach ( $filesByCategory as $category => $files ) {
805 foreach ( $files as $key => $fileInfo ) {
806 $expandedFileInfo = $this->expandFileInfo( $context, $fileInfo,
"$category\[$key]" );
807 $expandedFiles[$expandedFileInfo[
'name']] = $expandedFileInfo;
811 return $expandedFiles;
821 private function getLanguageScripts(
string $lang ): array {
822 $scripts = self::tryForKey( $this->languageScripts, $lang );
829 if ( $this->languageScripts ) {
831 ->getLanguageFallback()
832 ->getAll( $lang, LanguageFallback::MESSAGES );
833 foreach ( $fallbacks as $lang ) {
834 $scripts = self::tryForKey( $this->languageScripts, $lang );
845 $moduleName = $this->getName();
846 foreach ( $moduleSkinStyles as $skinName => $overrides ) {
849 if ( isset( $this->skinStyles[$skinName] ) ) {
855 if ( isset( $overrides[$moduleName] ) ) {
856 $paths = (array)$overrides[$moduleName];
858 } elseif ( isset( $overrides[
'+' . $moduleName] ) ) {
859 $paths = (array)$overrides[
'+' . $moduleName];
860 $styleFiles = isset( $this->skinStyles[
'default'] ) ?
861 (array)$this->skinStyles[
'default'] :
869 [ $localBasePath, $remoteBasePath ] = self::extractBasePaths( $overrides );
871 foreach ( $paths as
$path ) {
872 $styleFiles[] =
new FilePath(
$path, $localBasePath, $remoteBasePath );
875 $this->skinStyles[$skinName] = $styleFiles;
887 return array_merge_recursive(
888 self::collateStyleFilesByMedia( $this->styles ),
889 self::collateStyleFilesByMedia(
890 self::tryForKey( $this->skinStyles, $context->
getSkin(),
'default' )
903 return self::collateStyleFilesByMedia(
904 self::tryForKey( $this->skinStyles, $skinName )
915 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
918 $internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
919 $internalSkinNames[] =
'default';
921 foreach ( $internalSkinNames as $internalSkinName ) {
922 $styleFiles = array_merge_recursive(
924 $this->getSkinStyleFiles( $internalSkinName )
937 $collatedStyleFiles = array_merge_recursive(
938 self::collateStyleFilesByMedia( $this->styles ),
939 $this->getAllSkinStyleFiles()
944 foreach ( $collatedStyleFiles as $styleFiles ) {
945 foreach ( $styleFiles as $styleFile ) {
946 $result[] = $this->getLocalPath( $styleFile );
965 foreach ( $styles as $media => $files ) {
966 $uniqueFiles = array_unique( $files, SORT_REGULAR );
968 foreach ( $uniqueFiles as $file ) {
969 $styleFiles[] = $this->readStyleFile( $file, $context );
971 $styles[$media] = implode(
"\n", $styleFiles );
987 $localPath = $this->getLocalPath(
$path );
988 $style = $this->getFileContents( $localPath,
'style' );
989 $styleLang = $this->getStyleSheetLang( $localPath );
991 return $this->processStyle( $style, $styleLang,
$path, $context );
1011 $localPath = $this->getLocalPath(
$path );
1012 $remotePath = $this->getRemotePath(
$path );
1014 if ( $styleLang ===
'less' ) {
1015 $style = $this->compileLessString( $style, $localPath, $context );
1016 $this->hasGeneratedStyles =
true;
1019 if ( $this->getFlip( $context ) ) {
1020 $style = CSSJanus::transform(
1025 $this->hasGeneratedStyles =
true;
1028 $localDir = dirname( $localPath );
1029 $remoteDir = dirname( $remotePath );
1031 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
1032 foreach ( $localFileRefs as $file ) {
1033 if ( is_file( $file ) ) {
1034 $this->localFileRefs[] = $file;
1036 $this->missingLocalFileRefs[] = $file;
1041 return CSSMin::remap( $style, $localDir, $remoteDir,
true );
1050 return $context->
getDirection() ===
'rtl' && !$this->noflip;
1060 $canBeStylesOnly = !(
1063 || $this->debugScripts
1065 || $this->languageScripts
1066 || $this->skinScripts
1067 || $this->dependencies
1069 || $this->skipFunction
1070 || $this->packageFiles
1072 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
1090 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()
1094 $skinName = $context->
getSkin();
1095 $skinImportPaths = ExtensionRegistry::getInstance()->getAttribute(
'SkinLessImportPaths' );
1097 if ( isset( $skinImportPaths[ $skinName ] ) ) {
1098 $importDirs[] = $skinImportPaths[ $skinName ];
1101 $vars = $this->getLessVars( $context );
1107 'importDirs' => $importDirs,
1110 'codexDevDir' => $this->getConfig()->get( MainConfigNames::CodexDevelopmentDir )
1112 $key = $cache->makeGlobalKey(
1113 'resourceloader-less',
1115 hash(
'md4', $style ),
1116 hash(
'md4', serialize( $compilerParams ) )
1121 $data = $cache->get( $key );
1124 $data[
'hash'] !== FileContentsHasher::getFileContentsHash( $data[
'files'] )
1126 $compiler = $context->
getResourceLoader()->getLessCompiler( $vars, $importDirs );
1128 $css = $compiler->parse( $style, $stylePath )->getCss();
1132 $files = $compiler->getParsedFiles();
1135 'files' => Module::getRelativePaths( $files ),
1136 'hash' => FileContentsHasher::getFileContentsHash( $files )
1138 $cache->set( $key, $data, $cache::TTL_DAY );
1141 foreach ( Module::expandRelativePaths( $data[
'files'] ) as
$path ) {
1142 $this->localFileRefs[] =
$path;
1145 return $data[
'css'];
1156 foreach ( $this->templates as $alias => $templatePath ) {
1158 if ( is_int( $alias ) ) {
1159 $alias = $this->getPath( $templatePath );
1161 $localPath = $this->getLocalPath( $templatePath );
1162 $content = $this->getFileContents( $localPath,
'template' );
1164 $templates[$alias] = $this->stripBom( $content );
1188 private function expandPackageFiles(
Context $context ) {
1190 if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1191 return $this->expandedPackageFiles[$hash];
1193 if ( $this->packageFiles ===
null ) {
1196 $expandedFiles = [];
1199 foreach ( $this->packageFiles as $key => $fileInfo ) {
1200 $expanded = $this->expandFileInfo( $context, $fileInfo,
"packageFiles[$key]" );
1201 $fileName = $expanded[
'name'];
1202 if ( !empty( $expanded[
'main'] ) ) {
1203 unset( $expanded[
'main'] );
1204 $type = $expanded[
'type'];
1205 $mainFile = $fileName;
1206 if ( $type !==
'script' && $type !==
'script-vue' ) {
1207 $msg =
"Main file in package must be of type 'script', module " .
1208 "'{$this->getName()}', main file '{$mainFile}' is '{$type}'.";
1209 $this->getLogger()->error( $msg );
1210 throw new LogicException( $msg );
1213 $expandedFiles[$fileName] = $expanded;
1216 if ( $expandedFiles && $mainFile ===
null ) {
1218 foreach ( $expandedFiles as
$path => $file ) {
1219 if ( $file[
'type'] ===
'script' || $file[
'type'] ===
'script-vue' ) {
1227 'main' => $mainFile,
1228 'files' => $expandedFiles
1231 $this->expandedPackageFiles[$hash] = $result;
1264 private function expandFileInfo( Context $context, $fileInfo, $debugKey ) {
1265 if ( is_string( $fileInfo ) ) {
1268 'name' => $fileInfo,
1269 'type' => self::getPackageFileType( $fileInfo ),
1270 'filePath' =>
new FilePath( $fileInfo, $this->localBasePath, $this->remoteBasePath )
1272 } elseif ( $fileInfo instanceof FilePath ) {
1274 'name' => $fileInfo->getPath(),
1277 } elseif ( !is_array( $fileInfo ) ) {
1278 $msg =
"Invalid type in $debugKey for module '{$this->getName()}', " .
1279 "must be array, string or FilePath";
1280 $this->getLogger()->error( $msg );
1281 throw new LogicException( $msg );
1283 if ( !isset( $fileInfo[
'name'] ) ) {
1284 $msg =
"Missing 'name' key in $debugKey for module '{$this->getName()}'";
1285 $this->getLogger()->error( $msg );
1286 throw new LogicException( $msg );
1288 $fileName = $this->getPath( $fileInfo[
'name'] );
1291 $type = $fileInfo[
'type'] ?? self::getPackageFileType( $fileName );
1293 'name' => $fileName,
1296 if ( !empty( $fileInfo[
'main'] ) ) {
1297 $expanded[
'main'] =
true;
1304 if ( isset( $fileInfo[
'content'] ) ) {
1305 $expanded[
'content'] = $fileInfo[
'content'];
1306 } elseif ( isset( $fileInfo[
'file'] ) ) {
1307 $expanded[
'filePath'] = $this->makeFilePath( $fileInfo[
'file'] );
1308 } elseif ( isset( $fileInfo[
'callback'] ) ) {
1310 $expanded[
'callbackParam'] = $fileInfo[
'callbackParam'] ??
null;
1312 if ( !is_callable( $fileInfo[
'callback'] ) ) {
1313 $msg =
"Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
1314 $this->getLogger()->error( $msg );
1315 throw new LogicException( $msg );
1317 if ( isset( $fileInfo[
'versionCallback'] ) ) {
1318 if ( !is_callable( $fileInfo[
'versionCallback'] ) ) {
1319 throw new LogicException(
"Invalid 'versionCallback' for "
1320 .
"module '{$this->getName()}', file '{$fileName}'."
1326 $callbackResult = ( $fileInfo[
'versionCallback'] )(
1329 $expanded[
'callbackParam']
1331 if ( $callbackResult instanceof FilePath ) {
1332 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1333 $expanded[
'versionFilePath'] = $callbackResult;
1335 $expanded[
'definitionSummary'] = $callbackResult;
1338 $expanded[
'callback'] = $fileInfo[
'callback'];
1341 $callbackResult = ( $fileInfo[
'callback'] )(
1344 $expanded[
'callbackParam']
1346 if ( $callbackResult instanceof FilePath ) {
1347 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1348 $expanded[
'filePath'] = $callbackResult;
1350 $expanded[
'content'] = $callbackResult;
1353 } elseif ( isset( $fileInfo[
'config'] ) ) {
1354 if ( $type !==
'data' ) {
1355 $msg =
"Key 'config' only valid for data files. "
1356 .
" Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
1357 $this->getLogger()->error( $msg );
1358 throw new LogicException( $msg );
1360 $expandedConfig = [];
1361 foreach ( $fileInfo[
'config'] as $configKey => $var ) {
1362 $expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
1364 $expanded[
'content'] = $expandedConfig;
1365 } elseif ( !empty( $fileInfo[
'main'] ) ) {
1367 $expanded[
'filePath'] = $this->makeFilePath( $fileName );
1369 $msg =
"Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
1370 .
"One of 'file', 'content', 'callback', or 'config' must be set.";
1371 $this->getLogger()->error( $msg );
1372 throw new LogicException( $msg );
1374 if ( !isset( $expanded[
'filePath'] ) ) {
1375 $expanded[
'virtualFilePath'] = $this->makeFilePath( $fileName );
1386 private function makeFilePath(
$path ): FilePath {
1387 if (
$path instanceof FilePath ) {
1389 } elseif ( is_string(
$path ) ) {
1390 return new FilePath(
$path, $this->localBasePath, $this->remoteBasePath );
1392 throw new InvalidArgumentException(
'$path must be either FilePath or string' );
1403 if ( $this->packageFiles ===
null ) {
1407 if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
1408 return $this->fullyExpandedPackageFiles[ $hash ];
1410 $expandedPackageFiles = $this->expandPackageFiles( $context ) ?? [];
1412 foreach ( $expandedPackageFiles[
'files'] as &$fileInfo ) {
1413 $this->readFileInfo( $context, $fileInfo );
1416 $this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
1417 return $expandedPackageFiles;
1428 private function readFileInfo(
Context $context, array &$fileInfo ) {
1433 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'callback'] ) ) {
1434 $callbackResult = ( $fileInfo[
'callback'] )(
1437 $fileInfo[
'callbackParam']
1439 if ( $callbackResult instanceof
FilePath ) {
1441 $fileInfo[
'filePath'] = $callbackResult;
1443 $fileInfo[
'content'] = $callbackResult;
1445 unset( $fileInfo[
'callback'] );
1452 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'filePath'] ) ) {
1453 $localPath = $this->getLocalPath( $fileInfo[
'filePath'] );
1454 $content = $this->getFileContents( $localPath,
'package' );
1455 if ( $fileInfo[
'type'] ===
'data' ) {
1456 $content = json_decode( $content,
false, 512, JSON_THROW_ON_ERROR );
1458 $fileInfo[
'content'] = $content;
1460 if ( $fileInfo[
'type'] ===
'script-vue' ) {
1462 $parsedComponent = $this->getVueComponentParser()->parse(
1464 $fileInfo[
'content'],
1465 [
'minifyTemplate' => !$context->
getDebug() ]
1467 }
catch ( TimeoutException $e ) {
1469 }
catch ( Exception $e ) {
1470 $msg =
"Error parsing file '{$fileInfo['name']}' in module '{$this->getName()}': " .
1472 $this->getLogger()->error( $msg );
1473 throw new RuntimeException( $msg );
1475 $encodedTemplate = json_encode( $parsedComponent[
'template'] );
1480 $encodedTemplate = preg_replace(
'/(?<!\\\\)\\\\n/',
" \\n\\\n", $encodedTemplate );
1482 $encodedTemplate = strtr( $encodedTemplate, [
"\\t" =>
"\t" ] );
1484 $fileInfo[
'content'] = [
1485 'script' => $parsedComponent[
'script'] .
1486 ";\nmodule.exports.template = $encodedTemplate;",
1487 'style' => $parsedComponent[
'style'] ??
'',
1488 'styleLang' => $parsedComponent[
'styleLang'] ??
'css'
1490 $fileInfo[
'type'] =
'script+style';
1492 if ( !isset( $fileInfo[
'content'] ) ) {
1494 $msg =
"Unable to resolve contents for file {$fileInfo['name']}";
1495 $this->getLogger()->error( $msg );
1496 throw new RuntimeException( $msg );
1500 unset( $fileInfo[
'definitionSummary'] );
1502 unset( $fileInfo[
'callbackParam'] );
1516 if ( str_starts_with( $input,
"\xef\xbb\xbf" ) ) {
1517 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 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'.