2 namespace TYPO3\CMS\Core\Package
;
5 * This file is part of the TYPO3 CMS project.
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use Symfony\Component\Finder\Finder
;
18 use Symfony\Component\Finder\SplFileInfo
;
19 use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
;
20 use TYPO3\CMS\Core\Core\ClassLoadingInformation
;
21 use TYPO3\CMS\Core\Core\Environment
;
22 use TYPO3\CMS\Core\Service\DependencyOrderingService
;
23 use TYPO3\CMS\Core\Service\OpcodeCacheService
;
24 use TYPO3\CMS\Core\SingletonInterface
;
25 use TYPO3\CMS\Core\Utility\ArrayUtility
;
26 use TYPO3\CMS\Core\Utility\GeneralUtility
;
27 use TYPO3\CMS\Core\Utility\PathUtility
;
30 * The default TYPO3 Package Manager
32 class PackageManager
implements SingletonInterface
35 * @var DependencyOrderingService
37 protected $dependencyOrderingService;
40 * @var FrontendInterface
47 protected $cacheIdentifier;
52 protected $packagesBasePaths = [];
57 protected $packageAliasMap = [];
62 protected $runtimeActivatedPackages = [];
65 * Absolute path leading to the various package directories
68 protected $packagesBasePath;
71 * Array of available packages, indexed by package key
72 * @var PackageInterface[]
74 protected $packages = [];
79 protected $availablePackagesScanned = false;
82 * A map between ComposerName and PackageKey, only available when scanAvailablePackages is run
85 protected $composerNameToPackageKeyMap = [];
88 * List of active packages as package key => package object
91 protected $activePackages = [];
96 protected $packageStatesPathAndFilename;
99 * Package states configuration as stored in the PackageStates.php file
102 protected $packageStatesConfiguration = [];
105 * @param DependencyOrderingService $dependencyOrderingService
107 public function __construct(DependencyOrderingService
$dependencyOrderingService)
109 $this->packagesBasePath
= Environment
::getPublicPath() . '/';
110 $this->packageStatesPathAndFilename
= Environment
::getLegacyConfigPath() . '/PackageStates.php';
111 $this->dependencyOrderingService
= $dependencyOrderingService;
115 * @param FrontendInterface $coreCache
118 public function injectCoreCache(FrontendInterface
$coreCache)
120 $this->coreCache
= $coreCache;
124 * Initializes the package manager
127 public function initialize()
130 $this->loadPackageManagerStatesFromCache();
131 } catch (Exception\PackageManagerCacheUnavailableException
$exception) {
132 $this->loadPackageStates();
133 $this->initializePackageObjects();
134 $this->saveToPackageCache();
141 protected function getCacheIdentifier()
143 if ($this->cacheIdentifier
=== null) {
144 $mTime = @filemtime
($this->packageStatesPathAndFilename
);
145 if ($mTime !== false) {
146 $this->cacheIdentifier
= md5(TYPO3_version
. $this->packageStatesPathAndFilename
. $mTime);
148 $this->cacheIdentifier
= null;
151 return $this->cacheIdentifier
;
157 protected function getCacheEntryIdentifier()
159 $cacheIdentifier = $this->getCacheIdentifier();
160 return $cacheIdentifier !== null ?
'PackageManager_' . $cacheIdentifier : null;
164 * Saves the current state of all relevant information to the TYPO3 Core Cache
166 protected function saveToPackageCache()
168 $cacheEntryIdentifier = $this->getCacheEntryIdentifier();
169 if ($cacheEntryIdentifier !== null && !$this->coreCache
->has($cacheEntryIdentifier)) {
172 'packageStatesConfiguration' => $this->packageStatesConfiguration
,
173 'packageAliasMap' => $this->packageAliasMap
,
174 'composerNameToPackageKeyMap' => $this->composerNameToPackageKeyMap
,
175 'packageObjects' => serialize($this->packages
),
177 $this->coreCache
->set(
178 $cacheEntryIdentifier,
179 'return ' . PHP_EOL
. var_export($packageCache, true) . ';'
185 * Attempts to load the package manager states from cache
187 * @throws Exception\PackageManagerCacheUnavailableException
189 protected function loadPackageManagerStatesFromCache()
191 $cacheEntryIdentifier = $this->getCacheEntryIdentifier();
192 if ($cacheEntryIdentifier === null ||
!$this->coreCache
->has($cacheEntryIdentifier) ||
!($packageCache = $this->coreCache
->require($cacheEntryIdentifier))) {
193 throw new Exception\
PackageManagerCacheUnavailableException('The package state cache could not be loaded.', 1393883342);
195 $this->packageStatesConfiguration
= $packageCache['packageStatesConfiguration'];
196 if ($this->packageStatesConfiguration
['version'] < 5) {
197 throw new Exception\
PackageManagerCacheUnavailableException('The package state cache could not be loaded.', 1393883341);
199 $this->packageAliasMap
= $packageCache['packageAliasMap'];
200 $this->composerNameToPackageKeyMap
= $packageCache['composerNameToPackageKeyMap'];
201 $this->packages
= unserialize($packageCache['packageObjects'], [
202 'allowed_classes' => [
205 MetaData\PackageConstraint
::class,
212 * Loads the states of available packages from the PackageStates.php file.
213 * The result is stored in $this->packageStatesConfiguration.
215 * @throws Exception\PackageStatesUnavailableException
217 protected function loadPackageStates()
219 $forcePackageStatesRewrite = false;
220 $this->packageStatesConfiguration
= @include
$this->packageStatesPathAndFilename ?
: [];
221 if (!isset($this->packageStatesConfiguration
['version']) ||
$this->packageStatesConfiguration
['version'] < 4) {
222 $this->packageStatesConfiguration
= [];
223 } elseif ($this->packageStatesConfiguration
['version'] === 4) {
224 // Convert to v5 format which only includes a list of active packages.
225 // Deprecated since version 8, will be removed in version 10.
226 $activePackages = [];
227 foreach ($this->packageStatesConfiguration
['packages'] as $packageKey => $packageConfiguration) {
228 if ($packageConfiguration['state'] !== 'active') {
231 $activePackages[$packageKey] = ['packagePath' => $packageConfiguration['packagePath']];
233 $this->packageStatesConfiguration
['packages'] = $activePackages;
234 $this->packageStatesConfiguration
['version'] = 5;
235 $forcePackageStatesRewrite = true;
237 if ($this->packageStatesConfiguration
!== []) {
238 $this->registerPackagesFromConfiguration($this->packageStatesConfiguration
['packages'], false, $forcePackageStatesRewrite);
240 throw new Exception\
PackageStatesUnavailableException('The PackageStates.php file is either corrupt or unavailable.', 1381507733);
245 * Initializes activePackages property
247 * Saves PackageStates.php if list of required extensions has changed.
249 protected function initializePackageObjects()
251 $requiredPackages = [];
252 $activePackages = [];
253 foreach ($this->packages
as $packageKey => $package) {
254 if ($package->isProtected()) {
255 $requiredPackages[$packageKey] = $package;
257 if (isset($this->packageStatesConfiguration
['packages'][$packageKey])) {
258 $activePackages[$packageKey] = $package;
261 $previousActivePackages = $activePackages;
262 $activePackages = array_merge($requiredPackages, $activePackages);
264 if ($activePackages != $previousActivePackages) {
265 foreach ($requiredPackages as $requiredPackageKey => $package) {
266 $this->registerActivePackage($package);
268 $this->sortAndSavePackageStates();
273 * @param PackageInterface $package
275 protected function registerActivePackage(PackageInterface
$package)
277 // reset the active packages so they are rebuilt.
278 $this->activePackages
= [];
279 $this->packageStatesConfiguration
['packages'][$package->getPackageKey()] = ['packagePath' => str_replace($this->packagesBasePath
, '', $package->getPackagePath())];
283 * Scans all directories in the packages directories for available packages.
284 * For each package a Package object is created and stored in $this->packages.
287 public function scanAvailablePackages()
289 $packagePaths = $this->scanPackagePathsForExtensions();
291 foreach ($packagePaths as $packageKey => $packagePath) {
293 $composerManifest = $this->getComposerManifest($packagePath);
294 $packageKey = $this->getPackageKeyFromManifest($composerManifest, $packagePath);
295 $this->composerNameToPackageKeyMap
[strtolower($composerManifest->name
)] = $packageKey;
296 $packages[$packageKey] = ['packagePath' => str_replace($this->packagesBasePath
, '', $packagePath)];
297 } catch (Exception\MissingPackageManifestException
$exception) {
298 if (!$this->isPackageKeyValid($packageKey)) {
301 } catch (Exception\InvalidPackageKeyException
$exception) {
306 $this->availablePackagesScanned
= true;
307 $registerOnlyNewPackages = !empty($this->packages
);
308 $this->registerPackagesFromConfiguration($packages, $registerOnlyNewPackages);
312 * Scans all directories for a certain package.
314 * @param string $packageKey
315 * @return PackageInterface
317 protected function registerPackageDuringRuntime($packageKey)
319 $packagePaths = $this->scanPackagePathsForExtensions();
320 $packagePath = $packagePaths[$packageKey];
321 $composerManifest = $this->getComposerManifest($packagePath);
322 $packageKey = $this->getPackageKeyFromManifest($composerManifest, $packagePath);
323 $this->composerNameToPackageKeyMap
[strtolower($composerManifest->name
)] = $packageKey;
324 $packagePath = PathUtility
::sanitizeTrailingSeparator($packagePath);
325 $package = new Package($this, $packageKey, $packagePath);
326 $this->registerPackage($package);
331 * Fetches all directories from sysext/global/local locations and checks if the extension contains an ext_emconf.php
335 protected function scanPackagePathsForExtensions()
337 $collectedExtensionPaths = [];
338 foreach ($this->getPackageBasePaths() as $packageBasePath) {
339 // Only add the extension if we have an EMCONF and the extension is not yet registered.
340 // This is crucial in order to allow overriding of system extension by local extensions
341 // and strongly depends on the order of paths defined in $this->packagesBasePaths.
342 $finder = new Finder();
344 ->name('ext_emconf.php')
347 ->ignoreUnreadableDirs()
348 ->in($packageBasePath);
350 /** @var SplFileInfo $fileInfo */
351 foreach ($finder as $fileInfo) {
352 $path = PathUtility
::dirname($fileInfo->getPathname());
353 $extensionName = PathUtility
::basename($path);
354 // Fix Windows backslashes
355 // we can't use GeneralUtility::fixWindowsFilePath as we have to keep double slashes for Unit Tests (vfs://)
356 $currentPath = str_replace('\\', '/', $path) . '/';
357 if (!isset($collectedExtensionPaths[$extensionName])) {
358 $collectedExtensionPaths[$extensionName] = $currentPath;
362 return $collectedExtensionPaths;
366 * Requires and registers all packages which were defined in packageStatesConfiguration
368 * @param array $packages
369 * @param bool $registerOnlyNewPackages
370 * @param bool $packageStatesHasChanged
371 * @throws Exception\InvalidPackageStateException
372 * @throws Exception\PackageStatesFileNotWritableException
374 protected function registerPackagesFromConfiguration(array $packages, $registerOnlyNewPackages = false, $packageStatesHasChanged = false)
376 foreach ($packages as $packageKey => $stateConfiguration) {
377 if ($registerOnlyNewPackages && $this->isPackageRegistered($packageKey)) {
381 if (!isset($stateConfiguration['packagePath'])) {
382 $this->unregisterPackageByPackageKey($packageKey);
383 $packageStatesHasChanged = true;
388 $packagePath = PathUtility
::sanitizeTrailingSeparator($this->packagesBasePath
. $stateConfiguration['packagePath']);
389 $package = new Package($this, $packageKey, $packagePath);
390 } catch (Exception\InvalidPackagePathException
$exception) {
391 $this->unregisterPackageByPackageKey($packageKey);
392 $packageStatesHasChanged = true;
394 } catch (Exception\InvalidPackageKeyException
$exception) {
395 $this->unregisterPackageByPackageKey($packageKey);
396 $packageStatesHasChanged = true;
398 } catch (Exception\InvalidPackageManifestException
$exception) {
399 $this->unregisterPackageByPackageKey($packageKey);
400 $packageStatesHasChanged = true;
404 $this->registerPackage($package);
406 if ($packageStatesHasChanged) {
407 $this->sortAndSavePackageStates();
412 * Register a native TYPO3 package
414 * @param PackageInterface $package The Package to be registered
415 * @return PackageInterface
416 * @throws Exception\InvalidPackageStateException
419 public function registerPackage(PackageInterface
$package)
421 $packageKey = $package->getPackageKey();
422 if ($this->isPackageRegistered($packageKey)) {
423 throw new Exception\
InvalidPackageStateException('Package "' . $packageKey . '" is already registered.', 1338996122);
426 $this->packages
[$packageKey] = $package;
428 if ($package instanceof PackageInterface
) {
429 foreach ($package->getPackageReplacementKeys() as $packageToReplace => $versionConstraint) {
430 $this->packageAliasMap
[strtolower($packageToReplace)] = $package->getPackageKey();
437 * Unregisters a package from the list of available packages
439 * @param string $packageKey Package Key of the package to be unregistered
441 protected function unregisterPackageByPackageKey($packageKey)
444 $package = $this->getPackage($packageKey);
445 if ($package instanceof PackageInterface
) {
446 foreach ($package->getPackageReplacementKeys() as $packageToReplace => $versionConstraint) {
447 unset($this->packageAliasMap
[strtolower($packageToReplace)]);
450 } catch (Exception\UnknownPackageException
$e) {
452 unset($this->packages
[$packageKey]);
453 unset($this->packageStatesConfiguration
['packages'][$packageKey]);
457 * Resolves a TYPO3 package key from a composer package name.
459 * @param string $composerName
463 public function getPackageKeyFromComposerName($composerName)
465 $lowercasedComposerName = strtolower($composerName);
466 if (isset($this->packageAliasMap
[$lowercasedComposerName])) {
467 return $this->packageAliasMap
[$lowercasedComposerName];
469 if (isset($this->composerNameToPackageKeyMap
[$lowercasedComposerName])) {
470 return $this->composerNameToPackageKeyMap
[$lowercasedComposerName];
472 return $composerName;
476 * Returns a PackageInterface object for the specified package.
477 * A package is available, if the package directory contains valid MetaData information.
479 * @param string $packageKey
480 * @return PackageInterface The requested package object
481 * @throws Exception\UnknownPackageException if the specified package is not known
483 public function getPackage($packageKey)
485 if (!$this->isPackageRegistered($packageKey) && !$this->isPackageAvailable($packageKey)) {
486 throw new Exception\
UnknownPackageException('Package "' . $packageKey . '" is not available. Please check if the package exists and that the package key is correct (package keys are case sensitive).', 1166546734);
488 return $this->packages
[$packageKey];
492 * Returns TRUE if a package is available (the package's files exist in the packages directory)
493 * or FALSE if it's not. If a package is available it doesn't mean necessarily that it's active!
495 * @param string $packageKey The key of the package to check
496 * @return bool TRUE if the package is available, otherwise FALSE
498 public function isPackageAvailable($packageKey)
500 if ($this->isPackageRegistered($packageKey)) {
504 // If activePackages is empty, the PackageManager is currently initializing
505 // thus packages should not be scanned
506 if (!$this->availablePackagesScanned
&& !empty($this->activePackages
)) {
507 $this->scanAvailablePackages();
510 return $this->isPackageRegistered($packageKey);
514 * Returns TRUE if a package is activated or FALSE if it's not.
516 * @param string $packageKey The key of the package to check
517 * @return bool TRUE if package is active, otherwise FALSE
519 public function isPackageActive($packageKey)
521 $packageKey = $this->getPackageKeyFromComposerName($packageKey);
523 return isset($this->runtimeActivatedPackages
[$packageKey]) ||
isset($this->packageStatesConfiguration
['packages'][$packageKey]);
527 * Deactivates a package and updates the packagestates configuration
529 * @param string $packageKey
530 * @throws Exception\PackageStatesFileNotWritableException
531 * @throws Exception\ProtectedPackageKeyException
532 * @throws Exception\UnknownPackageException
535 public function deactivatePackage($packageKey)
537 $packagesWithDependencies = $this->sortActivePackagesByDependencies();
539 foreach ($packagesWithDependencies as $packageStateKey => $packageStateConfiguration) {
540 if ($packageKey === $packageStateKey ||
empty($packageStateConfiguration['dependencies'])) {
543 if (in_array($packageKey, $packageStateConfiguration['dependencies'], true)) {
544 $this->deactivatePackage($packageStateKey);
548 if (!$this->isPackageActive($packageKey)) {
552 $package = $this->getPackage($packageKey);
553 if ($package->isProtected()) {
554 throw new Exception\
ProtectedPackageKeyException('The package "' . $packageKey . '" is protected and cannot be deactivated.', 1308662891);
557 $this->activePackages
= [];
558 unset($this->packageStatesConfiguration
['packages'][$packageKey]);
559 $this->sortAndSavePackageStates();
563 * @param string $packageKey
566 public function activatePackage($packageKey)
568 $package = $this->getPackage($packageKey);
569 $this->registerTransientClassLoadingInformationForPackage($package);
571 if ($this->isPackageActive($packageKey)) {
575 $this->registerActivePackage($package);
576 $this->sortAndSavePackageStates();
580 * Enables packages during runtime, but no class aliases will be available
582 * @param string $packageKey
584 public function activatePackageDuringRuntime($packageKey)
586 $package = $this->registerPackageDuringRuntime($packageKey);
587 $this->runtimeActivatedPackages
[$package->getPackageKey()] = $package;
588 $this->registerTransientClassLoadingInformationForPackage($package);
592 * @param PackageInterface $package
593 * @throws \TYPO3\CMS\Core\Exception
595 protected function registerTransientClassLoadingInformationForPackage(PackageInterface
$package)
597 if (Environment
::isComposerMode()) {
600 ClassLoadingInformation
::registerTransientClassLoadingInformationForPackage($package);
604 * Removes a package from the file system.
606 * @param string $packageKey
608 * @throws Exception\ProtectedPackageKeyException
609 * @throws Exception\UnknownPackageException
612 public function deletePackage($packageKey)
614 if (!$this->isPackageAvailable($packageKey)) {
615 throw new Exception\
UnknownPackageException('Package "' . $packageKey . '" is not available and cannot be removed.', 1166543253);
618 $package = $this->getPackage($packageKey);
619 if ($package->isProtected()) {
620 throw new Exception\
ProtectedPackageKeyException('The package "' . $packageKey . '" is protected and cannot be removed.', 1220722120);
623 if ($this->isPackageActive($packageKey)) {
624 $this->deactivatePackage($packageKey);
627 $this->unregisterPackage($package);
628 $this->sortAndSavePackageStates();
630 $packagePath = $package->getPackagePath();
631 $deletion = GeneralUtility
::rmdir($packagePath, true);
632 if ($deletion === false) {
633 throw new Exception('Please check file permissions. The directory "' . $packagePath . '" for package "' . $packageKey . '" could not be removed.', 1301491089);
638 * Returns an array of \TYPO3\CMS\Core\Package objects of all active packages.
639 * A package is active, if it is available and has been activated in the package
640 * manager settings. This method returns runtime activated packages too
642 * @return PackageInterface[]
644 public function getActivePackages()
646 if (empty($this->activePackages
)) {
647 if (!empty($this->packageStatesConfiguration
['packages'])) {
648 foreach ($this->packageStatesConfiguration
['packages'] as $packageKey => $packageConfig) {
649 $this->activePackages
[$packageKey] = $this->getPackage($packageKey);
653 return array_merge($this->activePackages
, $this->runtimeActivatedPackages
);
657 * Returns TRUE if a package was already registered or FALSE if it's not.
659 * @param string $packageKey
662 protected function isPackageRegistered($packageKey)
664 $packageKey = $this->getPackageKeyFromComposerName($packageKey);
666 return isset($this->packages
[$packageKey]);
670 * Orders all active packages by comparing their dependencies. By this, the packages
671 * and package configurations arrays holds all packages in the correct
672 * initialization order.
676 protected function sortActivePackagesByDependencies()
678 $packagesWithDependencies = $this->resolvePackageDependencies($this->packageStatesConfiguration
['packages']);
680 // sort the packages by key at first, so we get a stable sorting of "equivalent" packages afterwards
681 ksort($packagesWithDependencies);
682 $sortedPackageKeys = $this->sortPackageStatesConfigurationByDependency($packagesWithDependencies);
684 // Reorder the packages according to the loading order
685 $this->packageStatesConfiguration
['packages'] = [];
686 foreach ($sortedPackageKeys as $packageKey) {
687 $this->registerActivePackage($this->packages
[$packageKey]);
689 return $packagesWithDependencies;
693 * Resolves the dependent packages from the meta data of all packages recursively. The
694 * resolved direct or indirect dependencies of each package will put into the package
695 * states configuration array.
697 * @param $packageConfig
700 protected function resolvePackageDependencies($packageConfig)
702 $packagesWithDependencies = [];
703 foreach ($packageConfig as $packageKey => $_) {
704 $packagesWithDependencies[$packageKey]['dependencies'] = $this->getDependencyArrayForPackage($packageKey);
705 $packagesWithDependencies[$packageKey]['suggestions'] = $this->getSuggestionArrayForPackage($packageKey);
707 return $packagesWithDependencies;
711 * Returns an array of suggested package keys for the given package.
713 * @param string $packageKey The package key to fetch the suggestions for
714 * @return array|null An array of directly suggested packages
716 protected function getSuggestionArrayForPackage($packageKey)
718 if (!isset($this->packages
[$packageKey])) {
721 $suggestedPackageKeys = [];
722 $suggestedPackageConstraints = $this->packages
[$packageKey]->getPackageMetaData()->getConstraintsByType(MetaData
::CONSTRAINT_TYPE_SUGGESTS
);
723 foreach ($suggestedPackageConstraints as $constraint) {
724 if ($constraint instanceof MetaData\PackageConstraint
) {
725 $suggestedPackageKey = $constraint->getValue();
726 if (isset($this->packages
[$suggestedPackageKey])) {
727 $suggestedPackageKeys[] = $suggestedPackageKey;
731 return array_reverse($suggestedPackageKeys);
735 * Saves the current content of $this->packageStatesConfiguration to the
736 * PackageStates.php file.
738 * @throws Exception\PackageStatesFileNotWritableException
740 protected function savePackageStates()
742 $this->packageStatesConfiguration
['version'] = 5;
744 $fileDescription = "# PackageStates.php\n\n";
745 $fileDescription .= "# This file is maintained by TYPO3's package management. Although you can edit it\n";
746 $fileDescription .= "# manually, you should rather use the extension manager for maintaining packages.\n";
747 $fileDescription .= "# This file will be regenerated automatically if it doesn't exist. Deleting this file\n";
748 $fileDescription .= "# should, however, never become necessary if you use the package commands.\n";
750 if (!@is_writable
($this->packageStatesPathAndFilename
)) {
751 // If file does not exists try to create it
752 $fileHandle = @fopen
($this->packageStatesPathAndFilename
, 'x');
754 throw new Exception\
PackageStatesFileNotWritableException(
755 sprintf('We could not update the list of installed packages because the file %s is not writable. Please, check the file system permissions for this file and make sure that the web server can update it.', $this->packageStatesPathAndFilename
),
761 $packageStatesCode = "<?php\n$fileDescription\nreturn " . ArrayUtility
::arrayExport($this->packageStatesConfiguration
) . ";\n";
762 GeneralUtility
::writeFile($this->packageStatesPathAndFilename
, $packageStatesCode, true);
764 GeneralUtility
::makeInstance(OpcodeCacheService
::class)->clearAllActive($this->packageStatesPathAndFilename
);
768 * Saves the current content of $this->packageStatesConfiguration to the
769 * PackageStates.php file.
771 * @throws Exception\PackageStatesFileNotWritableException
773 protected function sortAndSavePackageStates()
775 $this->sortActivePackagesByDependencies();
776 $this->savePackageStates();
780 * Check the conformance of the given package key
782 * @param string $packageKey The package key to validate
783 * @return bool If the package key is valid, returns TRUE otherwise FALSE
785 public function isPackageKeyValid($packageKey)
787 return preg_match(PackageInterface
::PATTERN_MATCH_PACKAGEKEY
, $packageKey) === 1 ||
preg_match(PackageInterface
::PATTERN_MATCH_EXTENSIONKEY
, $packageKey) === 1;
791 * Returns an array of \TYPO3\CMS\Core\Package objects of all available packages.
792 * A package is available, if the package directory contains valid meta information.
794 * @return PackageInterface[] Array of PackageInterface
796 public function getAvailablePackages()
798 if ($this->availablePackagesScanned
=== false) {
799 $this->scanAvailablePackages();
802 return $this->packages
;
806 * Unregisters a package from the list of available packages
808 * @param PackageInterface $package The package to be unregistered
809 * @throws Exception\InvalidPackageStateException
812 public function unregisterPackage(PackageInterface
$package)
814 $packageKey = $package->getPackageKey();
815 if (!$this->isPackageRegistered($packageKey)) {
816 throw new Exception\
InvalidPackageStateException('Package "' . $packageKey . '" is not registered.', 1338996142);
818 $this->unregisterPackageByPackageKey($packageKey);
822 * Reloads a package and its information
824 * @param string $packageKey
825 * @throws Exception\InvalidPackageStateException if the package isn't available
828 public function reloadPackageInformation($packageKey)
830 if (!$this->isPackageRegistered($packageKey)) {
831 throw new Exception\
InvalidPackageStateException('Package "' . $packageKey . '" is not registered.', 1436201329);
834 /** @var PackageInterface $package */
835 $package = $this->packages
[$packageKey];
836 $packagePath = $package->getPackagePath();
837 $newPackage = new Package($this, $packageKey, $packagePath);
838 $this->packages
[$packageKey] = $newPackage;
843 * Returns contents of Composer manifest as a stdObject
845 * @param string $manifestPath
847 * @throws Exception\InvalidPackageManifestException
850 public function getComposerManifest($manifestPath)
852 $composerManifest = null;
853 if (file_exists($manifestPath . 'composer.json')) {
854 $json = file_get_contents($manifestPath . 'composer.json');
855 $composerManifest = json_decode($json);
856 if (!$composerManifest instanceof \stdClass
) {
857 throw new Exception\
InvalidPackageManifestException('The composer.json found for extension "' . PathUtility
::basename($manifestPath) . '" is invalid!', 1439555561);
861 $extensionManagerConfiguration = $this->getExtensionEmConf($manifestPath);
862 $composerManifest = $this->mapExtensionManagerConfigurationToComposerManifest(
863 PathUtility
::basename($manifestPath),
864 $extensionManagerConfiguration,
865 $composerManifest ?
: new \
stdClass()
868 return $composerManifest;
872 * Fetches MetaData information from ext_emconf.php, used for
873 * resolving dependencies as well.
875 * @param string $packagePath
877 * @throws Exception\InvalidPackageManifestException
879 protected function getExtensionEmConf($packagePath)
881 $packageKey = PathUtility
::basename($packagePath);
882 $_EXTKEY = $packageKey;
883 $path = $packagePath . 'ext_emconf.php';
885 if (@file_exists
($path)) {
887 if (is_array($EM_CONF[$_EXTKEY])) {
888 return $EM_CONF[$_EXTKEY];
891 throw new Exception\
InvalidPackageManifestException('No valid ext_emconf.php file found for package "' . $packageKey . '".', 1360403545);
895 * Fetches information from ext_emconf.php and maps it so it is treated as it would come from composer.json
897 * @param string $packageKey
898 * @param array $extensionManagerConfiguration
899 * @param \stdClass $composerManifest
901 * @throws Exception\InvalidPackageManifestException
903 protected function mapExtensionManagerConfigurationToComposerManifest($packageKey, array $extensionManagerConfiguration, \stdClass
$composerManifest)
905 $this->setComposerManifestValueIfEmpty($composerManifest, 'name', $packageKey);
906 $this->setComposerManifestValueIfEmpty($composerManifest, 'type', 'typo3-cms-extension');
907 $this->setComposerManifestValueIfEmpty($composerManifest, 'description', $extensionManagerConfiguration['title'] ??
'');
908 $this->setComposerManifestValueIfEmpty($composerManifest, 'authors', [['name' => $extensionManagerConfiguration['author'] ??
'', 'email' => $extensionManagerConfiguration['author_email'] ??
'']]);
909 $composerManifest->version
= $extensionManagerConfiguration['version'] ??
'';
910 if (isset($extensionManagerConfiguration['constraints']['depends']) && is_array($extensionManagerConfiguration['constraints']['depends'])) {
911 $composerManifest->require = new \
stdClass();
912 foreach ($extensionManagerConfiguration['constraints']['depends'] as $requiredPackageKey => $requiredPackageVersion) {
913 if (!empty($requiredPackageKey)) {
914 if ($requiredPackageKey === 'typo3') {
915 // Add implicit dependency to 'core'
916 $composerManifest->require->core
= $requiredPackageVersion;
917 } elseif ($requiredPackageKey !== 'php') {
918 // Skip php dependency
919 $composerManifest->require->{$requiredPackageKey} = $requiredPackageVersion;
922 throw new Exception\
InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in depends section. Extension key is missing!', $packageKey), 1439552058);
926 if (isset($extensionManagerConfiguration['constraints']['conflicts']) && is_array($extensionManagerConfiguration['constraints']['conflicts'])) {
927 $composerManifest->conflict
= new \
stdClass();
928 foreach ($extensionManagerConfiguration['constraints']['conflicts'] as $conflictingPackageKey => $conflictingPackageVersion) {
929 if (!empty($conflictingPackageKey)) {
930 $composerManifest->conflict
->$conflictingPackageKey = $conflictingPackageVersion;
932 throw new Exception\
InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in conflicts section. Extension key is missing!', $packageKey), 1439552059);
936 if (isset($extensionManagerConfiguration['constraints']['suggests']) && is_array($extensionManagerConfiguration['constraints']['suggests'])) {
937 $composerManifest->suggest
= new \
stdClass();
938 foreach ($extensionManagerConfiguration['constraints']['suggests'] as $suggestedPackageKey => $suggestedPackageVersion) {
939 if (!empty($suggestedPackageKey)) {
940 $composerManifest->suggest
->$suggestedPackageKey = $suggestedPackageVersion;
942 throw new Exception\
InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in suggests section. Extension key is missing!', $packageKey), 1439552060);
946 if (isset($extensionManagerConfiguration['autoload'])) {
947 $composerManifest->autoload
= json_decode(json_encode($extensionManagerConfiguration['autoload']));
949 // composer.json autoload-dev information must be discarded, as it may contain information only available after a composer install
950 unset($composerManifest->{'autoload-dev'});
951 if (isset($extensionManagerConfiguration['autoload-dev'])) {
952 $composerManifest->{'autoload-dev'} = json_decode(json_encode($extensionManagerConfiguration['autoload-dev']));
955 return $composerManifest;
959 * @param \stdClass $manifest
960 * @param string $property
961 * @param mixed $value
964 protected function setComposerManifestValueIfEmpty(\stdClass
$manifest, $property, $value)
966 if (empty($manifest->{$property})) {
967 $manifest->{$property} = $value;
974 * Returns an array of dependent package keys for the given package. It will
975 * do this recursively, so dependencies of dependent packages will also be
978 * @param string $packageKey The package key to fetch the dependencies for
979 * @param array $dependentPackageKeys
980 * @param array $trace An array of already visited package keys, to detect circular dependencies
981 * @return array|null An array of direct or indirect dependent packages
982 * @throws Exception\InvalidPackageKeyException
984 protected function getDependencyArrayForPackage($packageKey, array &$dependentPackageKeys = [], array $trace = [])
986 if (!isset($this->packages
[$packageKey])) {
989 if (in_array($packageKey, $trace, true) !== false) {
990 return $dependentPackageKeys;
992 $trace[] = $packageKey;
993 $dependentPackageConstraints = $this->packages
[$packageKey]->getPackageMetaData()->getConstraintsByType(MetaData
::CONSTRAINT_TYPE_DEPENDS
);
994 foreach ($dependentPackageConstraints as $constraint) {
995 if ($constraint instanceof MetaData\PackageConstraint
) {
996 $dependentPackageKey = $constraint->getValue();
997 if (in_array($dependentPackageKey, $dependentPackageKeys, true) === false && in_array($dependentPackageKey, $trace, true) === false) {
998 $dependentPackageKeys[] = $dependentPackageKey;
1000 $this->getDependencyArrayForPackage($dependentPackageKey, $dependentPackageKeys, $trace);
1003 return array_reverse($dependentPackageKeys);
1007 * Resolves package key from Composer manifest
1009 * If it is a TYPO3 package the name of the containing directory will be used.
1011 * Else if the composer name of the package matches the first part of the lowercased namespace of the package, the mixed
1012 * case version of the composer name / namespace will be used, with backslashes replaced by dots.
1014 * Else the composer name will be used with the slash replaced by a dot
1016 * @param object $manifest
1017 * @param string $packagePath
1018 * @throws Exception\InvalidPackageManifestException
1021 protected function getPackageKeyFromManifest($manifest, $packagePath)
1023 if (!is_object($manifest)) {
1024 throw new Exception\
InvalidPackageManifestException('Invalid composer manifest in package path: ' . $packagePath, 1348146451);
1026 if (isset($manifest->type
) && strpos($manifest->type
, 'typo3-cms-') === 0) {
1027 $packageKey = PathUtility
::basename($packagePath);
1028 return preg_replace('/[^A-Za-z0-9._-]/', '', $packageKey);
1030 $packageKey = str_replace('/', '.', $manifest->name
);
1031 return preg_replace('/[^A-Za-z0-9.]/', '', $packageKey);
1035 * The order of paths is crucial for allowing overriding of system extension by local extensions.
1036 * Pay attention if you change order of the paths here.
1040 protected function getPackageBasePaths()
1042 if (count($this->packagesBasePaths
) < 3) {
1043 // Check if the directory even exists and if it is not empty
1044 if (is_dir(Environment
::getExtensionsPath()) && $this->hasSubDirectories(Environment
::getExtensionsPath())) {
1045 $this->packagesBasePaths
['local'] = Environment
::getExtensionsPath() . '/*/';
1047 if (is_dir(Environment
::getBackendPath() . '/ext') && $this->hasSubDirectories(Environment
::getBackendPath() . '/ext')) {
1048 $this->packagesBasePaths
['global'] = Environment
::getBackendPath() . '/ext/*/';
1050 $this->packagesBasePaths
['system'] = Environment
::getFrameworkBasePath() . '/*/';
1052 return $this->packagesBasePaths
;
1056 * Returns true if the given path has valid subdirectories, false otherwise.
1058 * @param string $path
1061 protected function hasSubDirectories(string $path): bool
1063 return !empty(glob(rtrim($path, '/\\') . '/*', GLOB_ONLYDIR
));
1067 * @param array $packageStatesConfiguration
1068 * @return array Returns the packageStatesConfiguration sorted by dependencies
1069 * @throws \UnexpectedValueException
1071 protected function sortPackageStatesConfigurationByDependency(array $packageStatesConfiguration)
1073 return $this->dependencyOrderingService
->calculateOrder($this->buildDependencyGraph($packageStatesConfiguration));
1077 * Convert the package configuration into a dependency definition
1079 * This converts "dependencies" and "suggestions" to "after" syntax for the usage in DependencyOrderingService
1081 * @param array $packageStatesConfiguration
1082 * @param array $packageKeys
1084 * @throws \UnexpectedValueException
1086 protected function convertConfigurationForGraph(array $packageStatesConfiguration, array $packageKeys)
1089 foreach ($packageKeys as $packageKey) {
1090 if (!isset($packageStatesConfiguration[$packageKey]['dependencies']) && !isset($packageStatesConfiguration[$packageKey]['suggestions'])) {
1093 $dependencies[$packageKey] = [
1096 if (isset($packageStatesConfiguration[$packageKey]['dependencies'])) {
1097 foreach ($packageStatesConfiguration[$packageKey]['dependencies'] as $dependentPackageKey) {
1098 if (!in_array($dependentPackageKey, $packageKeys, true)) {
1099 throw new \
UnexpectedValueException(
1100 'The package "' . $packageKey . '" depends on "'
1101 . $dependentPackageKey . '" which is not present in the system.',
1105 $dependencies[$packageKey]['after'][] = $dependentPackageKey;
1108 if (isset($packageStatesConfiguration[$packageKey]['suggestions'])) {
1109 foreach ($packageStatesConfiguration[$packageKey]['suggestions'] as $suggestedPackageKey) {
1110 // skip suggestions on not existing packages
1111 if (in_array($suggestedPackageKey, $packageKeys, true)) {
1112 // Suggestions actually have never been meant to influence loading order.
1113 // We misuse this currently, as there is no other way to influence the loading order
1114 // for not-required packages (soft-dependency).
1115 // When considering suggestions for the loading order, we might create a cyclic dependency
1116 // if the suggested package already has a real dependency on this package, so the suggestion
1117 // has do be dropped in this case and must *not* be taken into account for loading order evaluation.
1118 $dependencies[$packageKey]['after-resilient'][] = $suggestedPackageKey;
1123 return $dependencies;
1127 * Adds all root packages of current dependency graph as dependency to all extensions
1129 * This ensures that the framework extensions (aka sysext) are
1130 * always loaded first, before any other external extension.
1132 * @param array $packageStateConfiguration
1133 * @param array $rootPackageKeys
1136 protected function addDependencyToFrameworkToAllExtensions(array $packageStateConfiguration, array $rootPackageKeys)
1138 $frameworkPackageKeys = $this->findFrameworkPackages($packageStateConfiguration);
1139 $extensionPackageKeys = array_diff(array_keys($packageStateConfiguration), $frameworkPackageKeys);
1140 foreach ($extensionPackageKeys as $packageKey) {
1141 // Remove framework packages from list
1142 $packageKeysWithoutFramework = array_diff(
1143 $packageStateConfiguration[$packageKey]['dependencies'],
1144 $frameworkPackageKeys
1146 // The order of the array_merge is crucial here,
1147 // we want the framework first
1148 $packageStateConfiguration[$packageKey]['dependencies'] = array_merge(
1150 $packageKeysWithoutFramework
1153 return $packageStateConfiguration;
1157 * Builds the dependency graph for all packages
1159 * This method also introduces dependencies among the dependencies
1160 * to ensure the loading order is exactly as specified in the list.
1162 * @param array $packageStateConfiguration
1165 protected function buildDependencyGraph(array $packageStateConfiguration)
1167 $frameworkPackageKeys = $this->findFrameworkPackages($packageStateConfiguration);
1168 $frameworkPackagesDependencyGraph = $this->dependencyOrderingService
->buildDependencyGraph($this->convertConfigurationForGraph($packageStateConfiguration, $frameworkPackageKeys));
1169 $packageStateConfiguration = $this->addDependencyToFrameworkToAllExtensions($packageStateConfiguration, $this->dependencyOrderingService
->findRootIds($frameworkPackagesDependencyGraph));
1171 $packageKeys = array_keys($packageStateConfiguration);
1172 return $this->dependencyOrderingService
->buildDependencyGraph($this->convertConfigurationForGraph($packageStateConfiguration, $packageKeys));
1176 * @param array $packageStateConfiguration
1179 protected function findFrameworkPackages(array $packageStateConfiguration)
1181 $frameworkPackageKeys = [];
1182 foreach ($packageStateConfiguration as $packageKey => $packageConfiguration) {
1183 $package = $this->getPackage($packageKey);
1184 if ($package->getValueFromComposerManifest('type') === 'typo3-cms-framework') {
1185 $frameworkPackageKeys[] = $packageKey;
1189 return $frameworkPackageKeys;