29use InvalidArgumentException;
37use Wikimedia\Minify\CSSMin;
38use Wikimedia\RequestTimeout\TimeoutException;
103 private $expandedPackageFiles = [];
109 private $fullyExpandedPackageFiles = [];
175 $hasTemplates =
false;
182 foreach ( $options as $member => $option ) {
189 $this->{$member} = is_array( $option ) ? $option : [ $option ];
192 $hasTemplates =
true;
193 $this->{$member} = is_array( $option ) ? $option : [ $option ];
196 case 'languageScripts':
199 if ( !is_array( $option ) ) {
200 throw new InvalidArgumentException(
201 "Invalid collated file path list error. " .
202 "'$option' given, array expected."
205 foreach ( $option as $key => $value ) {
206 if ( !is_string( $key ) ) {
207 throw new InvalidArgumentException(
208 "Invalid collated file path list key error. " .
209 "'$key' given, string expected."
212 $this->{$member}[$key] = is_array( $value ) ? $value : [ $value ];
216 $this->deprecated = $option;
223 $option = array_values( array_unique( (array)$option ) );
226 $this->{$member} = $option;
231 $this->{$member} = (string)$option;
236 $this->{$member} = (bool)$option;
240 if ( isset( $options[
'scripts'] ) && isset( $options[
'packageFiles'] ) ) {
241 throw new InvalidArgumentException(
"A module may not set both 'scripts' and 'packageFiles'" );
243 if ( isset( $options[
'packageFiles'] ) && isset( $options[
'skinScripts'] ) ) {
244 throw new InvalidArgumentException(
"Options 'skinScripts' and 'packageFiles' cannot be used together." );
246 if ( $hasTemplates ) {
247 $this->dependencies[] =
'mediawiki.template';
249 foreach ( $this->templates as $alias => $templatePath ) {
250 if ( is_int( $alias ) ) {
251 $alias = $this->
getPath( $templatePath );
253 $suffix = explode(
'.', $alias );
254 $suffix = end( $suffix );
255 $compilerModule =
'mediawiki.template.' . $suffix;
256 if ( $suffix !==
'html' && !in_array( $compilerModule, $this->dependencies ) ) {
257 $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();
382 private function hasGeneratedScripts() {
384 [ $this->scripts, $this->languageScripts, $this->skinScripts, $this->debugScripts ]
388 if ( is_array( $script ) ) {
389 if ( isset( $script[
'callback'] ) || isset( $script[
'versionCallback'] ) ) {
413 if (
$file[
'type'] ===
'script+style' ) {
415 $file[
'content'][
'style'],
416 $file[
'content'][
'styleLang'],
437 if ( $this->hasGeneratedStyles ) {
440 return parent::getStyleURLsForDebug( $context );
445 foreach ( $this->
getStyleFiles( $context ) as $mediaType => $list ) {
446 $urls[$mediaType] = [];
447 foreach ( $list as
$file ) {
448 $urls[$mediaType][] = OutputPage::transformResourcePath(
492 private function getFileContents( $localPath, $type ) {
493 if ( !is_file( $localPath ) ) {
494 throw new RuntimeException(
"$type file not found or not a file: \"$localPath\"" );
496 return $this->
stripBom( file_get_contents( $localPath ) );
503 if ( !$this->skipFunction ) {
506 $localPath = $this->
getLocalPath( $this->skipFunction );
507 return $this->getFileContents( $localPath,
'skip function' );
532 private function getFileHashes(
Context $context ) {
536 foreach ( $filePaths as $filePath ) {
544 $expandedPackageFiles = $this->expandPackageFiles( $context );
545 if ( $expandedPackageFiles ) {
546 foreach ( $expandedPackageFiles[
'files'] as $fileInfo ) {
547 if ( isset( $fileInfo[
'filePath'] ) ) {
549 $filePath = $fileInfo[
'filePath'];
550 $files[] = $filePath->getLocalPath();
556 $scriptFileInfos = $this->getScriptFiles( $context );
557 foreach ( $scriptFileInfos as $fileInfo ) {
558 $filePath = $fileInfo[
'filePath'] ?? $fileInfo[
'versionFilePath'] ??
null;
559 if ( $filePath instanceof FilePath ) {
560 $files[] = $filePath->getLocalPath();
564 foreach ( $this->templates as $filePath ) {
568 if ( $this->skipFunction ) {
580 $files = array_unique( $files );
596 $summary = parent::getDefinitionSummary( $context );
614 $options[$member] = $this->{$member};
618 $packageSummaries = [];
628 foreach (
$packageFiles[
'files'] as $fileName => $fileInfo ) {
629 $packageSummaries[$fileName] =
630 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
634 $scriptFiles = $this->getScriptFiles( $context );
635 $scriptSummaries = [];
636 foreach ( $scriptFiles as $fileName => $fileInfo ) {
637 $scriptSummaries[$fileName] =
638 $fileInfo[
'definitionSummary'] ?? $fileInfo[
'content'] ??
null;
642 'options' => $options,
643 'packageFiles' => $packageSummaries,
644 'scripts' => $scriptSummaries,
645 'fileHashes' => $this->getFileHashes( $context ),
651 $summary[] = [
'lessVars' => $lessVars ];
661 if ( $this->vueComponentParser ===
null ) {
673 return $path->getPath();
685 if (
$path->getLocalBasePath() !==
null ) {
686 return $path->getLocalPath();
691 return "{$this->localBasePath}/$path";
700 if (
$path->getRemoteBasePath() !==
null ) {
701 return $path->getRemotePath();
706 if ( $this->remoteBasePath ===
'/' ) {
709 return "{$this->remoteBasePath}/$path";
721 return preg_match(
'/\.less$/i',
$path ) ?
'less' :
'css';
731 if ( preg_match(
'/\.json$/i',
$path ) ) {
734 if ( preg_match(
'/\.vue$/i',
$path ) ) {
747 private static function collateStyleFilesByMedia( array $list ) {
749 foreach ( $list as $key => $value ) {
750 if ( is_int( $key ) ) {
752 $collatedFiles[
'all'][] = $value;
753 } elseif ( is_array( $value ) ) {
755 $optionValue = $value[
'media'] ??
'all';
756 $collatedFiles[$optionValue][] = $key;
759 return $collatedFiles;
772 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
789 private function getScriptFiles(
Context $context ): array {
793 'scripts' => $this->scripts,
794 'languageScripts' => $this->getLanguageScripts( $context->getLanguage() ),
795 'skinScripts' => self::
tryForKey( $this->skinScripts, $context->getSkin(),
'default' ),
802 foreach ( $filesByCategory as $category => $files ) {
803 foreach ( $files as $key => $fileInfo ) {
804 $expandedFileInfo = $this->expandFileInfo( $context, $fileInfo,
"$category\[$key]" );
805 $expandedFiles[$expandedFileInfo[
'name']] = $expandedFileInfo;
809 return $expandedFiles;
819 private function getLanguageScripts(
string $lang ): array {
820 $scripts = self::tryForKey( $this->languageScripts, $lang );
827 if ( $this->languageScripts ) {
829 ->getLanguageFallback()
830 ->getAll( $lang, LanguageFallback::MESSAGES );
831 foreach ( $fallbacks as $lang ) {
832 $scripts = self::tryForKey( $this->languageScripts, $lang );
843 $moduleName = $this->getName();
844 foreach ( $moduleSkinStyles as $skinName => $overrides ) {
847 if ( isset( $this->skinStyles[$skinName] ) ) {
853 if ( isset( $overrides[$moduleName] ) ) {
854 $paths = (array)$overrides[$moduleName];
856 } elseif ( isset( $overrides[
'+' . $moduleName] ) ) {
857 $paths = (array)$overrides[
'+' . $moduleName];
858 $styleFiles = isset( $this->skinStyles[
'default'] ) ?
859 (array)$this->skinStyles[
'default'] :
867 [ $localBasePath, $remoteBasePath ] = self::extractBasePaths( $overrides );
869 foreach ( $paths as
$path ) {
870 $styleFiles[] =
new FilePath(
$path, $localBasePath, $remoteBasePath );
873 $this->skinStyles[$skinName] = $styleFiles;
885 return array_merge_recursive(
886 self::collateStyleFilesByMedia( $this->styles ),
887 self::collateStyleFilesByMedia(
888 self::tryForKey( $this->skinStyles, $context->
getSkin(),
'default' )
901 return self::collateStyleFilesByMedia(
902 self::tryForKey( $this->skinStyles, $skinName )
913 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
916 $internalSkinNames = array_keys( $skinFactory->getInstalledSkins() );
917 $internalSkinNames[] =
'default';
919 foreach ( $internalSkinNames as $internalSkinName ) {
920 $styleFiles = array_merge_recursive(
922 $this->getSkinStyleFiles( $internalSkinName )
935 $collatedStyleFiles = array_merge_recursive(
936 self::collateStyleFilesByMedia( $this->styles ),
937 $this->getAllSkinStyleFiles()
942 foreach ( $collatedStyleFiles as $styleFiles ) {
943 foreach ( $styleFiles as $styleFile ) {
944 $result[] = $this->getLocalPath( $styleFile );
963 foreach ( $styles as $media => $files ) {
964 $uniqueFiles = array_unique( $files, SORT_REGULAR );
966 foreach ( $uniqueFiles as
$file ) {
967 $styleFiles[] = $this->readStyleFile(
$file, $context );
969 $styles[$media] = implode(
"\n", $styleFiles );
985 $localPath = $this->getLocalPath(
$path );
986 $style = $this->getFileContents( $localPath,
'style' );
987 $styleLang = $this->getStyleSheetLang( $localPath );
989 return $this->processStyle( $style, $styleLang,
$path, $context );
1009 $localPath = $this->getLocalPath(
$path );
1010 $remotePath = $this->getRemotePath(
$path );
1012 if ( $styleLang ===
'less' ) {
1013 $style = $this->compileLessString( $style, $localPath, $context );
1014 $this->hasGeneratedStyles =
true;
1017 if ( $this->getFlip( $context ) ) {
1018 $style = CSSJanus::transform(
1025 $localDir = dirname( $localPath );
1026 $remoteDir = dirname( $remotePath );
1028 $localFileRefs = CSSMin::getLocalFileReferences( $style, $localDir );
1029 foreach ( $localFileRefs as
$file ) {
1030 if ( is_file(
$file ) ) {
1031 $this->localFileRefs[] =
$file;
1033 $this->missingLocalFileRefs[] =
$file;
1038 return CSSMin::remap( $style, $localDir, $remoteDir,
true );
1047 return $context->
getDirection() ===
'rtl' && !$this->noflip;
1056 return $this->targets;
1066 $canBeStylesOnly = !(
1069 || $this->debugScripts
1071 || $this->languageScripts
1072 || $this->skinScripts
1073 || $this->dependencies
1075 || $this->skipFunction
1076 || $this->packageFiles
1078 return $canBeStylesOnly ? self::LOAD_STYLES : self::LOAD_GENERAL;
1099 $skinName = $context->
getSkin();
1100 $skinImportPaths = ExtensionRegistry::getInstance()->getAttribute(
'SkinLessImportPaths' );
1102 if ( isset( $skinImportPaths[ $skinName ] ) ) {
1103 $importDirs[] = $skinImportPaths[ $skinName ];
1106 $vars = $this->getLessVars( $context );
1112 'importDirs' => $importDirs,
1114 $key = $cache->makeGlobalKey(
1115 'resourceloader-less',
1117 hash(
'md4', $style ),
1118 hash(
'md4', serialize( $compilerParams ) )
1123 $data = $cache->get( $key );
1126 $data[
'hash'] !== FileContentsHasher::getFileContentsHash( $data[
'files'] )
1128 $compiler = $context->
getResourceLoader()->getLessCompiler( $vars, $importDirs );
1130 $css = $compiler->parse( $style, $stylePath )->getCss();
1134 $files = $compiler->AllParsedFiles();
1137 'files' => Module::getRelativePaths( $files ),
1138 'hash' => FileContentsHasher::getFileContentsHash( $files )
1140 $cache->set( $key, $data, $cache::TTL_DAY );
1143 foreach ( Module::expandRelativePaths( $data[
'files'] ) as
$path ) {
1144 $this->localFileRefs[] =
$path;
1147 return $data[
'css'];
1158 foreach ( $this->templates as $alias => $templatePath ) {
1160 if ( is_int( $alias ) ) {
1161 $alias = $this->getPath( $templatePath );
1163 $localPath = $this->getLocalPath( $templatePath );
1164 $content = $this->getFileContents( $localPath,
'template' );
1166 $templates[$alias] = $this->stripBom(
$content );
1190 private function expandPackageFiles(
Context $context ) {
1192 if ( isset( $this->expandedPackageFiles[$hash] ) ) {
1193 return $this->expandedPackageFiles[$hash];
1195 if ( $this->packageFiles ===
null ) {
1198 $expandedFiles = [];
1201 foreach ( $this->packageFiles as $key => $fileInfo ) {
1202 $expanded = $this->expandFileInfo( $context, $fileInfo,
"packageFiles[$key]" );
1203 $fileName = $expanded[
'name'];
1204 if ( !empty( $expanded[
'main'] ) ) {
1205 unset( $expanded[
'main'] );
1206 $type = $expanded[
'type'];
1207 $mainFile = $fileName;
1208 if ( $type !==
'script' && $type !==
'script-vue' ) {
1209 $msg =
"Main file in package must be of type 'script', module " .
1210 "'{$this->getName()}', main file '{$mainFile}' is '{$type}'.";
1211 $this->getLogger()->error( $msg );
1212 throw new LogicException( $msg );
1215 $expandedFiles[$fileName] = $expanded;
1218 if ( $expandedFiles && $mainFile ===
null ) {
1220 foreach ( $expandedFiles as
$path =>
$file ) {
1221 if (
$file[
'type'] ===
'script' ||
$file[
'type'] ===
'script-vue' ) {
1229 'main' => $mainFile,
1230 'files' => $expandedFiles
1233 $this->expandedPackageFiles[$hash] = $result;
1266 private function expandFileInfo( Context $context, $fileInfo, $debugKey ) {
1267 if ( is_string( $fileInfo ) ) {
1270 'name' => $fileInfo,
1271 'type' => self::getPackageFileType( $fileInfo ),
1272 'filePath' =>
new FilePath( $fileInfo, $this->localBasePath, $this->remoteBasePath )
1274 } elseif ( $fileInfo instanceof FilePath ) {
1276 'name' => $fileInfo->getPath(),
1279 } elseif ( !is_array( $fileInfo ) ) {
1280 $msg =
"Invalid type in $debugKey for module '{$this->getName()}', " .
1281 "must be array, string or FilePath";
1282 $this->getLogger()->error( $msg );
1283 throw new LogicException( $msg );
1285 if ( !isset( $fileInfo[
'name'] ) ) {
1286 $msg =
"Missing 'name' key in $debugKey for module '{$this->getName()}'";
1287 $this->getLogger()->error( $msg );
1288 throw new LogicException( $msg );
1290 $fileName = $this->getPath( $fileInfo[
'name'] );
1293 $type = $fileInfo[
'type'] ?? self::getPackageFileType( $fileName );
1295 'name' => $fileName,
1298 if ( !empty( $fileInfo[
'main'] ) ) {
1299 $expanded[
'main'] =
true;
1306 if ( isset( $fileInfo[
'content'] ) ) {
1307 $expanded[
'content'] = $fileInfo[
'content'];
1308 } elseif ( isset( $fileInfo[
'file'] ) ) {
1309 $expanded[
'filePath'] = $this->makeFilePath( $fileInfo[
'file'] );
1310 } elseif ( isset( $fileInfo[
'callback'] ) ) {
1312 $expanded[
'callbackParam'] = $fileInfo[
'callbackParam'] ??
null;
1314 if ( !is_callable( $fileInfo[
'callback'] ) ) {
1315 $msg =
"Invalid 'callback' for module '{$this->getName()}', file '{$fileName}'.";
1316 $this->getLogger()->error( $msg );
1317 throw new LogicException( $msg );
1319 if ( isset( $fileInfo[
'versionCallback'] ) ) {
1320 if ( !is_callable( $fileInfo[
'versionCallback'] ) ) {
1321 throw new LogicException(
"Invalid 'versionCallback' for "
1322 .
"module '{$this->getName()}', file '{$fileName}'."
1328 $callbackResult = ( $fileInfo[
'versionCallback'] )(
1331 $expanded[
'callbackParam']
1333 if ( $callbackResult instanceof FilePath ) {
1334 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1335 $expanded[
'versionFilePath'] = $callbackResult;
1337 $expanded[
'definitionSummary'] = $callbackResult;
1340 $expanded[
'callback'] = $fileInfo[
'callback'];
1343 $callbackResult = ( $fileInfo[
'callback'] )(
1346 $expanded[
'callbackParam']
1348 if ( $callbackResult instanceof FilePath ) {
1349 $callbackResult->initBasePaths( $this->localBasePath, $this->remoteBasePath );
1350 $expanded[
'filePath'] = $callbackResult;
1352 $expanded[
'content'] = $callbackResult;
1355 } elseif ( isset( $fileInfo[
'config'] ) ) {
1356 if ( $type !==
'data' ) {
1357 $msg =
"Key 'config' only valid for data files. "
1358 .
" Module '{$this->getName()}', file '{$fileName}' is '{$type}'.";
1359 $this->getLogger()->error( $msg );
1360 throw new LogicException( $msg );
1362 $expandedConfig = [];
1363 foreach ( $fileInfo[
'config'] as $configKey => $var ) {
1364 $expandedConfig[ is_numeric( $configKey ) ? $var : $configKey ] = $this->getConfig()->get( $var );
1366 $expanded[
'content'] = $expandedConfig;
1367 } elseif ( !empty( $fileInfo[
'main'] ) ) {
1369 $expanded[
'filePath'] = $this->makeFilePath( $fileName );
1371 $msg =
"Incomplete definition for module '{$this->getName()}', file '{$fileName}'. "
1372 .
"One of 'file', 'content', 'callback', or 'config' must be set.";
1373 $this->getLogger()->error( $msg );
1374 throw new LogicException( $msg );
1376 if ( !isset( $expanded[
'filePath'] ) ) {
1377 $expanded[
'virtualFilePath'] = $this->makeFilePath( $fileName );
1388 private function makeFilePath(
$path ): FilePath {
1389 if (
$path instanceof FilePath ) {
1391 } elseif ( is_string(
$path ) ) {
1392 return new FilePath(
$path, $this->localBasePath, $this->remoteBasePath );
1394 throw new InvalidArgumentException(
'$path must be either FilePath or string' );
1405 if ( $this->packageFiles ===
null ) {
1409 if ( isset( $this->fullyExpandedPackageFiles[ $hash ] ) ) {
1410 return $this->fullyExpandedPackageFiles[ $hash ];
1412 $expandedPackageFiles = $this->expandPackageFiles( $context ) ?? [];
1414 foreach ( $expandedPackageFiles[
'files'] as &$fileInfo ) {
1415 $this->readFileInfo( $context, $fileInfo );
1418 $this->fullyExpandedPackageFiles[ $hash ] = $expandedPackageFiles;
1419 return $expandedPackageFiles;
1430 private function readFileInfo(
Context $context, array &$fileInfo ) {
1435 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'callback'] ) ) {
1436 $callbackResult = ( $fileInfo[
'callback'] )(
1439 $fileInfo[
'callbackParam']
1441 if ( $callbackResult instanceof
FilePath ) {
1443 $fileInfo[
'filePath'] = $callbackResult;
1445 $fileInfo[
'content'] = $callbackResult;
1447 unset( $fileInfo[
'callback'] );
1454 if ( !isset( $fileInfo[
'content'] ) && isset( $fileInfo[
'filePath'] ) ) {
1455 $localPath = $this->getLocalPath( $fileInfo[
'filePath'] );
1456 $content = $this->getFileContents( $localPath,
'package' );
1457 if ( $fileInfo[
'type'] ===
'data' ) {
1462 if ( $fileInfo[
'type'] ===
'script-vue' ) {
1464 $parsedComponent = $this->getVueComponentParser()->parse(
1466 $fileInfo[
'content'],
1467 [
'minifyTemplate' => !$context->
getDebug() ]
1469 }
catch ( TimeoutException $e ) {
1471 }
catch ( Exception $e ) {
1472 $msg =
"Error parsing file '{$fileInfo['name']}' in module '{$this->getName()}': " .
1474 $this->getLogger()->error( $msg );
1475 throw new RuntimeException( $msg );
1477 $encodedTemplate = json_encode( $parsedComponent[
'template'] );
1481 $encodedTemplate = preg_replace(
'/(?<!\\\\)\\\\n/',
" \\\n", $encodedTemplate );
1483 $encodedTemplate = strtr( $encodedTemplate, [
"\\t" =>
"\t" ] );
1485 $fileInfo[
'content'] = [
1486 'script' => $parsedComponent[
'script'] .
1487 ";\nmodule.exports.template = $encodedTemplate;",
1488 'style' => $parsedComponent[
'style'] ??
'',
1489 'styleLang' => $parsedComponent[
'styleLang'] ??
'css'
1491 $fileInfo[
'type'] =
'script+style';
1493 if ( !isset( $fileInfo[
'content'] ) ) {
1495 $msg =
"Unable to resolve contents for file {$fileInfo['name']}";
1496 $this->getLogger()->error( $msg );
1497 throw new RuntimeException( $msg );
1501 unset( $fileInfo[
'definitionSummary'] );
1503 unset( $fileInfo[
'callbackParam'] );
1517 if ( str_starts_with( $input,
"\xef\xbb\xbf" ) ) {
1518 return substr( $input, 3 );
1525class_alias( FileModule::class,
'ResourceLoaderFileModule' );
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'.
Functions to get cache objects.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.