3f874a3690e3912ae1b5b19e96ed2978bdbbb5aa
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Package / PackageManager.php
1 <?php
2 namespace TYPO3\CMS\Core\Package;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
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.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Compatibility\LoadedExtensionArrayElement;
18 use TYPO3\CMS\Core\Core\Bootstrap;
19 use TYPO3\CMS\Core\Core\ClassLoadingInformation;
20 use TYPO3\CMS\Core\Service\OpcodeCacheService;
21 use TYPO3\CMS\Core\Utility\ArrayUtility;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\PathUtility;
24 use TYPO3\CMS\Core\Utility\StringUtility;
25
26 /**
27 * The default TYPO3 Package Manager
28 * Adapted from FLOW for TYPO3 CMS
29 */
30 class PackageManager implements \TYPO3\CMS\Core\SingletonInterface
31 {
32 /**
33 * @var \TYPO3\CMS\Core\Package\DependencyResolver
34 */
35 protected $dependencyResolver;
36
37 /**
38 * @var Bootstrap
39 */
40 protected $bootstrap;
41
42 /**
43 * @var \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend
44 */
45 protected $coreCache;
46
47 /**
48 * @var string
49 */
50 protected $cacheIdentifier;
51
52 /**
53 * @var array
54 */
55 protected $packagesBasePaths = array();
56
57 /**
58 * @var array
59 */
60 protected $packageAliasMap = array();
61
62 /**
63 * @var array
64 */
65 protected $runtimeActivatedPackages = array();
66
67 /**
68 * Absolute path leading to the various package directories
69 * @var string
70 */
71 protected $packagesBasePath = PATH_site;
72
73 /**
74 * Array of available packages, indexed by package key
75 * @var PackageInterface[]
76 */
77 protected $packages = array();
78
79 /**
80 * A map between ComposerName and PackageKey, only available when scanAvailablePackages is run
81 * @var array
82 */
83 protected $composerNameToPackageKeyMap = array();
84
85 /**
86 * List of active packages as package key => package object
87 * @var array
88 */
89 protected $activePackages = array();
90
91 /**
92 * @var string
93 */
94 protected $packageStatesPathAndFilename;
95
96 /**
97 * Package states configuration as stored in the PackageStates.php file
98 * @var array
99 */
100 protected $packageStatesConfiguration = array();
101
102 /**
103 * Constructor
104 */
105 public function __construct()
106 {
107 // The order of paths is crucial for allowing overriding of system extension by local extensions.
108 // Pay attention if you change order of the paths here.
109 $this->packagesBasePaths = array(
110 'local' => PATH_typo3conf . 'ext',
111 'global' => PATH_typo3 . 'ext',
112 'sysext' => PATH_typo3 . 'sysext',
113 );
114 $this->packageStatesPathAndFilename = PATH_typo3conf . 'PackageStates.php';
115 }
116
117 /**
118 * @param \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend $coreCache
119 */
120 public function injectCoreCache(\TYPO3\CMS\Core\Cache\Frontend\PhpFrontend $coreCache)
121 {
122 $this->coreCache = $coreCache;
123 }
124
125 /**
126 * @param DependencyResolver
127 */
128 public function injectDependencyResolver(DependencyResolver $dependencyResolver)
129 {
130 $this->dependencyResolver = $dependencyResolver;
131 }
132
133 /**
134 * Initializes the package manager
135 *
136 * @param Bootstrap $bootstrap The current bootstrap
137 *
138 * @return void
139 */
140 public function initialize(Bootstrap $bootstrap)
141 {
142 $this->bootstrap = $bootstrap;
143
144 $loadedFromCache = false;
145 try {
146 $this->loadPackageManagerStatesFromCache();
147 $loadedFromCache = true;
148 } catch (Exception\PackageManagerCacheUnavailableException $exception) {
149 $this->loadPackageStates();
150 $this->initializePackageObjects();
151 $this->initializeCompatibilityLoadedExtArray();
152 }
153
154 if (!$loadedFromCache) {
155 $this->saveToPackageCache();
156 }
157 }
158
159 /**
160 * @return string
161 */
162 protected function getCacheIdentifier()
163 {
164 if ($this->cacheIdentifier === null) {
165 $mTime = @filemtime($this->packageStatesPathAndFilename);
166 if ($mTime !== false) {
167 $this->cacheIdentifier = md5($this->packageStatesPathAndFilename . $mTime);
168 } else {
169 $this->cacheIdentifier = null;
170 }
171 }
172 return $this->cacheIdentifier;
173 }
174
175 /**
176 * @return string
177 */
178 protected function getCacheEntryIdentifier()
179 {
180 $cacheIdentifier = $this->getCacheIdentifier();
181 return $cacheIdentifier !== null ? 'PackageManager_' . $cacheIdentifier : null;
182 }
183
184 /**
185 * Saves the current state of all relevant information to the TYPO3 Core Cache
186 */
187 protected function saveToPackageCache()
188 {
189 $cacheEntryIdentifier = $this->getCacheEntryIdentifier();
190 if ($cacheEntryIdentifier !== null && !$this->coreCache->has($cacheEntryIdentifier)) {
191 // Package objects get their own cache entry, so PHP does not have to parse the serialized string
192 $packageObjectsCacheEntryIdentifier = StringUtility::getUniqueId('PackageObjects_');
193 // Build cache file
194 $packageCache = array(
195 'packageStatesConfiguration' => $this->packageStatesConfiguration,
196 'packageAliasMap' => $this->packageAliasMap,
197 'activePackageKeys' => array_keys($this->activePackages),
198 'loadedExtArray' => $GLOBALS['TYPO3_LOADED_EXT'],
199 'packageObjectsCacheEntryIdentifier' => $packageObjectsCacheEntryIdentifier
200 );
201 $this->coreCache->set($packageObjectsCacheEntryIdentifier, serialize($this->packages));
202 $this->coreCache->set(
203 $cacheEntryIdentifier,
204 'return ' . PHP_EOL . var_export($packageCache, true) . ';'
205 );
206 }
207 }
208
209 /**
210 * Attempts to load the package manager states from cache
211 *
212 * @throws Exception\PackageManagerCacheUnavailableException
213 */
214 protected function loadPackageManagerStatesFromCache()
215 {
216 $cacheEntryIdentifier = $this->getCacheEntryIdentifier();
217 if ($cacheEntryIdentifier === null || !$this->coreCache->has($cacheEntryIdentifier) || !($packageCache = $this->coreCache->requireOnce($cacheEntryIdentifier))) {
218 throw new Exception\PackageManagerCacheUnavailableException('The package state cache could not be loaded.', 1393883342);
219 }
220 $this->packageStatesConfiguration = $packageCache['packageStatesConfiguration'];
221 $this->packageAliasMap = $packageCache['packageAliasMap'];
222 $GLOBALS['TYPO3_LOADED_EXT'] = $packageCache['loadedExtArray'];
223 $GLOBALS['TYPO3_currentPackageManager'] = $this;
224 // Strip off PHP Tags from Php Cache Frontend
225 $packageObjects = substr(substr($this->coreCache->get($packageCache['packageObjectsCacheEntryIdentifier']), 6), 0, -2);
226 $this->packages = unserialize($packageObjects);
227 foreach ($packageCache['activePackageKeys'] as $activePackageKey) {
228 $this->activePackages[$activePackageKey] = $this->packages[$activePackageKey];
229 }
230 unset($GLOBALS['TYPO3_currentPackageManager']);
231 }
232
233 /**
234 * Loads the states of available packages from the PackageStates.php file.
235 * The result is stored in $this->packageStatesConfiguration.
236 *
237 * @throws Exception\PackageStatesUnavailableException
238 * @return void
239 */
240 protected function loadPackageStates()
241 {
242 $this->packageStatesConfiguration = @include($this->packageStatesPathAndFilename) ?: array();
243 if (!isset($this->packageStatesConfiguration['version']) || $this->packageStatesConfiguration['version'] < 4) {
244 $this->packageStatesConfiguration = array();
245 }
246 if ($this->packageStatesConfiguration !== array()) {
247 $this->registerPackagesFromConfiguration();
248 } else {
249 throw new Exception\PackageStatesUnavailableException('The PackageStates.php file is either corrupt or unavailable.', 1381507733);
250 }
251 }
252
253 /**
254 * Initializes activePackages property
255 *
256 * Saves PackageStates.php if list of required extensions has changed.
257 *
258 * @return void
259 */
260 protected function initializePackageObjects()
261 {
262 $requiredPackages = array();
263 foreach ($this->packages as $packageKey => $package) {
264 if ($package->isProtected()) {
265 $requiredPackages[$packageKey] = $package;
266 }
267 if (isset($this->packageStatesConfiguration['packages'][$packageKey]['state']) && $this->packageStatesConfiguration['packages'][$packageKey]['state'] === 'active') {
268 $this->activePackages[$packageKey] = $package;
269 }
270 }
271 $previousActivePackages = $this->activePackages;
272 $this->activePackages = array_merge($requiredPackages, $this->activePackages);
273
274 if ($this->activePackages != $previousActivePackages) {
275 foreach ($requiredPackages as $requiredPackageKey => $package) {
276 $this->packageStatesConfiguration['packages'][$requiredPackageKey]['state'] = 'active';
277 }
278 $this->sortAndSavePackageStates();
279 }
280 }
281
282 /**
283 * Initializes a backwards compatibility $GLOBALS['TYPO3_LOADED_EXT'] array
284 *
285 * @return void
286 */
287 protected function initializeCompatibilityLoadedExtArray()
288 {
289 $loadedExtObj = new \TYPO3\CMS\Core\Compatibility\LoadedExtensionsArray($this);
290 $GLOBALS['TYPO3_LOADED_EXT'] = $loadedExtObj->toArray();
291 }
292
293 /**
294 * Scans all directories in the packages directories for available packages.
295 * For each package a Package object is created and stored in $this->packages.
296 *
297 * @return void
298 */
299 public function scanAvailablePackages()
300 {
301 $previousPackageStatesConfiguration = $this->packageStatesConfiguration;
302
303 if (isset($this->packageStatesConfiguration['packages'])) {
304 foreach ($this->packageStatesConfiguration['packages'] as $packageKey => $configuration) {
305 if (!@file_exists($this->packagesBasePath . $configuration['packagePath'])) {
306 unset($this->packageStatesConfiguration['packages'][$packageKey]);
307 }
308 }
309 } else {
310 $this->packageStatesConfiguration['packages'] = array();
311 }
312
313 foreach ($this->packagesBasePaths as $key => $packagesBasePath) {
314 if (!is_dir($packagesBasePath)) {
315 unset($this->packagesBasePaths[$key]);
316 }
317 }
318 $packagePaths = $this->scanPackagePathsForExtensions();
319 foreach ($packagePaths as $packagePath) {
320 $packagesBasePath = $this->packagesBasePath;
321 foreach ($this->packagesBasePaths as $basePath) {
322 if (strpos($packagePath, $basePath) === 0) {
323 $packagesBasePath = $basePath;
324 break;
325 }
326 }
327 try {
328 $composerManifest = $this->getComposerManifest($packagePath);
329 $packageKey = $this->getPackageKeyFromManifest($composerManifest, $packagePath, $packagesBasePath);
330 $this->composerNameToPackageKeyMap[strtolower($composerManifest->name)] = $packageKey;
331 $this->packageStatesConfiguration['packages'][$packageKey]['composerName'] = $composerManifest->name;
332 } catch (Exception\MissingPackageManifestException $exception) {
333 $relativePackagePath = substr($packagePath, strlen($packagesBasePath));
334 $packageKey = substr($relativePackagePath, strpos($relativePackagePath, '/') + 1, -1);
335 if (!$this->isPackageKeyValid($packageKey)) {
336 continue;
337 }
338 } catch (Exception\InvalidPackageKeyException $exception) {
339 continue;
340 }
341 if (!isset($this->packageStatesConfiguration['packages'][$packageKey]['state'])) {
342 $this->packageStatesConfiguration['packages'][$packageKey]['state'] = 'inactive';
343 }
344
345 $this->packageStatesConfiguration['packages'][$packageKey]['packagePath'] = str_replace($this->packagesBasePath, '', $packagePath);
346 }
347
348 $registerOnlyNewPackages = !empty($this->packages);
349 $this->registerPackagesFromConfiguration($registerOnlyNewPackages);
350 if ($this->packageStatesConfiguration != $previousPackageStatesConfiguration) {
351 $this->sortAndsavePackageStates();
352 }
353 }
354
355 /**
356 * Fetches all directories from sysext/global/local locations and checks if the extension contains an ext_emconf.php
357 *
358 * @return array
359 */
360 protected function scanPackagePathsForExtensions()
361 {
362 $collectedExtensionPaths = [];
363 foreach ($this->packagesBasePaths as $type => $packageBasePath) {
364 /** @var $fileInfo \SplFileInfo */
365 foreach (new \DirectoryIterator($packageBasePath) as $fileInfo) {
366 if (!$fileInfo->isDir()) {
367 continue;
368 }
369 $filename = $fileInfo->getFilename();
370 if ($filename[0] !== '.') {
371 // Fix Windows backslashes
372 // we can't use GeneralUtility::fixWindowsFilePath as we have to keep double slashes for Unit Tests (vfs://)
373 $currentPath = str_replace('\\', '/', $fileInfo->getPathName()) . '/';
374 // Only add the extension if we have an EMCONF and the extension is not yet registered.
375 // This is crucial in order to allow overriding of system extension by local extensions
376 // and strongly depends on the order of paths defined in $this->packagesBasePaths.
377 if (file_exists($currentPath . 'ext_emconf.php') && !isset($collectedExtensionPaths[$filename])) {
378 $collectedExtensionPaths[$filename] = $currentPath;
379 }
380 }
381 }
382 }
383 return $collectedExtensionPaths;
384 }
385
386 /**
387 * Requires and registers all packages which were defined in packageStatesConfiguration
388 *
389 * @param bool $registerOnlyNewPackages
390 * @return void
391 */
392 protected function registerPackagesFromConfiguration($registerOnlyNewPackages = false)
393 {
394 $packageStatesHasChanged = false;
395 foreach ($this->packageStatesConfiguration['packages'] as $packageKey => $stateConfiguration) {
396 if ($registerOnlyNewPackages && $this->isPackageAvailable($packageKey)) {
397 continue;
398 }
399
400 if (!isset($stateConfiguration['packagePath'])) {
401 $this->unregisterPackageByPackageKey($packageKey);
402 $packageStatesHasChanged = true;
403 continue;
404 }
405
406 try {
407 $packagePath = PathUtility::sanitizeTrailingSeparator($this->packagesBasePath . $stateConfiguration['packagePath']);
408 $package = new Package($this, $packageKey, $packagePath);
409 } catch (Exception\InvalidPackagePathException $exception) {
410 $this->unregisterPackageByPackageKey($packageKey);
411 $packageStatesHasChanged = true;
412 continue;
413 } catch (Exception\InvalidPackageKeyException $exception) {
414 $this->unregisterPackageByPackageKey($packageKey);
415 $packageStatesHasChanged = true;
416 continue;
417 } catch (Exception\InvalidPackageManifestException $exception) {
418 $this->unregisterPackageByPackageKey($packageKey);
419 $packageStatesHasChanged = true;
420 continue;
421 }
422
423 $this->registerPackage($package, false);
424
425 if ($stateConfiguration['state'] === 'active') {
426 $this->activePackages[$packageKey] = $this->packages[$packageKey];
427 }
428 }
429 if ($packageStatesHasChanged) {
430 $this->sortAndSavePackageStates();
431 }
432 }
433
434 /**
435 * Register a native TYPO3 package
436 *
437 * @param PackageInterface $package The Package to be registered
438 * @param bool $sortAndSave allows for not saving packagestates when used in loops etc.
439 * @return PackageInterface
440 * @throws Exception\InvalidPackageStateException
441 * @throws Exception\PackageStatesFileNotWritableException
442 */
443 public function registerPackage(PackageInterface $package, $sortAndSave = true)
444 {
445 $packageKey = $package->getPackageKey();
446 if ($this->isPackageAvailable($packageKey)) {
447 throw new Exception\InvalidPackageStateException('Package "' . $packageKey . '" is already registered.', 1338996122);
448 }
449
450 $this->packages[$packageKey] = $package;
451 $this->packageStatesConfiguration['packages'][$packageKey]['packagePath'] = str_replace($this->packagesBasePath, '', $package->getPackagePath());
452
453 if ($sortAndSave === true) {
454 $this->sortAndSavePackageStates();
455 }
456
457 if ($package instanceof PackageInterface) {
458 foreach ($package->getPackageReplacementKeys() as $packageToReplace => $versionConstraint) {
459 $this->packageAliasMap[strtolower($packageToReplace)] = $package->getPackageKey();
460 }
461 }
462 return $package;
463 }
464
465 /**
466 * Unregisters a package from the list of available packages
467 *
468 * @param string $packageKey Package Key of the package to be unregistered
469 * @return void
470 */
471 protected function unregisterPackageByPackageKey($packageKey)
472 {
473 try {
474 $package = $this->getPackage($packageKey);
475 if ($package instanceof PackageInterface) {
476 foreach ($package->getPackageReplacementKeys() as $packageToReplace => $versionConstraint) {
477 unset($this->packageAliasMap[strtolower($packageToReplace)]);
478 }
479 }
480 } catch (Exception\UnknownPackageException $e) {
481 }
482 unset($this->packages[$packageKey]);
483 unset($this->packageStatesConfiguration['packages'][$packageKey]);
484 }
485
486 /**
487 * Resolves a TYPO3 package key from a composer package name.
488 *
489 * @param string $composerName
490 * @return string
491 */
492 public function getPackageKeyFromComposerName($composerName)
493 {
494 if (isset($this->packageAliasMap[$composerName])) {
495 return $this->packageAliasMap[$composerName];
496 }
497 if (empty($this->composerNameToPackageKeyMap)) {
498 foreach ($this->packageStatesConfiguration['packages'] as $packageKey => $packageStateConfiguration) {
499 $this->composerNameToPackageKeyMap[strtolower($packageStateConfiguration['composerName'])] = $packageKey;
500 }
501 }
502 $lowercasedComposerName = strtolower($composerName);
503 if (!isset($this->composerNameToPackageKeyMap[$lowercasedComposerName])) {
504 return $composerName;
505 }
506 return $this->composerNameToPackageKeyMap[$lowercasedComposerName];
507 }
508
509 /**
510 * Returns a PackageInterface object for the specified package.
511 * A package is available, if the package directory contains valid MetaData information.
512 *
513 * @param string $packageKey
514 * @return PackageInterface The requested package object
515 * @throws Exception\UnknownPackageException if the specified package is not known
516 * @api
517 */
518 public function getPackage($packageKey)
519 {
520 if (isset($this->packageAliasMap[$lowercasedPackageKey = strtolower($packageKey)])) {
521 $packageKey = $this->packageAliasMap[$lowercasedPackageKey];
522 }
523 if (!$this->isPackageAvailable($packageKey)) {
524 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);
525 }
526 return $this->packages[$packageKey];
527 }
528
529 /**
530 * Returns TRUE if a package is available (the package's files exist in the packages directory)
531 * or FALSE if it's not. If a package is available it doesn't mean necessarily that it's active!
532 *
533 * @param string $packageKey The key of the package to check
534 * @return bool TRUE if the package is available, otherwise FALSE
535 * @api
536 */
537 public function isPackageAvailable($packageKey)
538 {
539 if (isset($this->packageAliasMap[$lowercasedPackageKey = strtolower($packageKey)])) {
540 $packageKey = $this->packageAliasMap[$lowercasedPackageKey];
541 }
542 return isset($this->packages[$packageKey]);
543 }
544
545 /**
546 * Returns TRUE if a package is activated or FALSE if it's not.
547 *
548 * @param string $packageKey The key of the package to check
549 * @return bool TRUE if package is active, otherwise FALSE
550 * @api
551 */
552 public function isPackageActive($packageKey)
553 {
554 return isset($this->runtimeActivatedPackages[$packageKey]) || isset($this->activePackages[$packageKey]);
555 }
556
557 /**
558 * Deactivates a package and updates the packagestates configuration
559 *
560 * @param string $packageKey
561 * @throws Exception\PackageStatesFileNotWritableException
562 * @throws Exception\ProtectedPackageKeyException
563 * @throws Exception\UnknownPackageException
564 */
565 public function deactivatePackage($packageKey)
566 {
567 $this->sortAvailablePackagesByDependencies();
568
569 foreach ($this->packageStatesConfiguration['packages'] as $packageStateKey => $packageStateConfiguration) {
570 if ($packageKey === $packageStateKey || empty($packageStateConfiguration['dependencies']) || $packageStateConfiguration['state'] !== 'active') {
571 continue;
572 }
573 if (in_array($packageKey, $packageStateConfiguration['dependencies'], true)) {
574 $this->deactivatePackage($packageStateKey);
575 }
576 }
577
578 if (!$this->isPackageActive($packageKey)) {
579 return;
580 }
581
582 $package = $this->getPackage($packageKey);
583 if ($package->isProtected()) {
584 throw new Exception\ProtectedPackageKeyException('The package "' . $packageKey . '" is protected and cannot be deactivated.', 1308662891);
585 }
586
587 unset($this->activePackages[$packageKey]);
588 $this->packageStatesConfiguration['packages'][$packageKey]['state'] = 'inactive';
589 $this->sortAndSavePackageStates();
590 }
591
592 /**
593 * @param string $packageKey
594 */
595 public function activatePackage($packageKey)
596 {
597 $package = $this->getPackage($packageKey);
598 $this->registerTransientClassLoadingInformationForPackage($package);
599
600 if ($this->isPackageActive($packageKey)) {
601 return;
602 }
603
604 $this->activePackages[$packageKey] = $package;
605 $this->packageStatesConfiguration['packages'][$packageKey]['state'] = 'active';
606 if (!isset($this->packageStatesConfiguration['packages'][$packageKey]['packagePath'])) {
607 $this->packageStatesConfiguration['packages'][$packageKey]['packagePath'] = str_replace($this->packagesBasePath, '', $package->getPackagePath());
608 }
609 $this->sortAndSavePackageStates();
610 }
611
612 /**
613 * Enables packages during runtime, but no class aliases will be available
614 *
615 * @param string $packageKey
616 * @api
617 */
618 public function activatePackageDuringRuntime($packageKey)
619 {
620 $package = $this->getPackage($packageKey);
621 $this->runtimeActivatedPackages[$package->getPackageKey()] = $package;
622 if (!isset($GLOBALS['TYPO3_LOADED_EXT'][$package->getPackageKey()])) {
623 $loadedExtArrayElement = new LoadedExtensionArrayElement($package);
624 $GLOBALS['TYPO3_LOADED_EXT'][$package->getPackageKey()] = $loadedExtArrayElement->toArray();
625 }
626 $this->registerTransientClassLoadingInformationForPackage($package);
627 }
628
629 /**
630 * @param PackageInterface $package
631 * @throws \TYPO3\CMS\Core\Exception
632 */
633 protected function registerTransientClassLoadingInformationForPackage(PackageInterface $package)
634 {
635 if (Bootstrap::usesComposerClassLoading()) {
636 return;
637 }
638 ClassLoadingInformation::registerTransientClassLoadingInformationForPackage($package);
639 }
640
641 /**
642 * Removes a package from the file system.
643 *
644 * @param string $packageKey
645 * @throws Exception
646 * @throws Exception\InvalidPackageStateException
647 * @throws Exception\ProtectedPackageKeyException
648 * @throws Exception\UnknownPackageException
649 */
650 public function deletePackage($packageKey)
651 {
652 if (!$this->isPackageAvailable($packageKey)) {
653 throw new Exception\UnknownPackageException('Package "' . $packageKey . '" is not available and cannot be removed.', 1166543253);
654 }
655
656 $package = $this->getPackage($packageKey);
657 if ($package->isProtected()) {
658 throw new Exception\ProtectedPackageKeyException('The package "' . $packageKey . '" is protected and cannot be removed.', 1220722120);
659 }
660
661 if ($this->isPackageActive($packageKey)) {
662 $this->deactivatePackage($packageKey);
663 }
664
665 $this->unregisterPackage($package);
666 $this->sortAndSavePackageStates();
667
668 $packagePath = $package->getPackagePath();
669 $deletion = GeneralUtility::rmdir($packagePath, true);
670 if ($deletion === false) {
671 throw new Exception('Please check file permissions. The directory "' . $packagePath . '" for package "' . $packageKey . '" could not be removed.', 1301491089);
672 }
673 }
674
675 /**
676 * Returns an array of \TYPO3\CMS\Core\Package objects of all active packages.
677 * A package is active, if it is available and has been activated in the package
678 * manager settings. This method returns runtime activated packages too
679 *
680 * @return PackageInterface[]
681 * @api
682 */
683 public function getActivePackages()
684 {
685 return array_merge($this->activePackages, $this->runtimeActivatedPackages);
686 }
687
688 /**
689 * Orders all packages by comparing their dependencies. By this, the packages
690 * and package configurations arrays holds all packages in the correct
691 * initialization order.
692 *
693 * @return void
694 */
695 protected function sortAvailablePackagesByDependencies()
696 {
697 $this->resolvePackageDependencies();
698
699 // sort the packages by key at first, so we get a stable sorting of "equivalent" packages afterwards
700 ksort($this->packageStatesConfiguration['packages']);
701 $this->packageStatesConfiguration['packages'] = $this->dependencyResolver->sortPackageStatesConfigurationByDependency($this->packageStatesConfiguration['packages']);
702
703 // Reorder the packages according to the loading order
704 $newPackages = array();
705 foreach ($this->packageStatesConfiguration['packages'] as $packageKey => $_) {
706 $newPackages[$packageKey] = $this->packages[$packageKey];
707 }
708 $this->packages = $newPackages;
709 }
710
711 /**
712 * Resolves the dependent packages from the meta data of all packages recursively. The
713 * resolved direct or indirect dependencies of each package will put into the package
714 * states configuration array.
715 *
716 * @return void
717 */
718 protected function resolvePackageDependencies()
719 {
720 foreach ($this->packages as $packageKey => $package) {
721 $this->packageStatesConfiguration['packages'][$packageKey]['dependencies'] = $this->getDependencyArrayForPackage($packageKey);
722 }
723 foreach ($this->packages as $packageKey => $package) {
724 $this->packageStatesConfiguration['packages'][$packageKey]['suggestions'] = $this->getSuggestionArrayForPackage($packageKey);
725 }
726 }
727
728 /**
729 * Returns an array of suggested package keys for the given package.
730 *
731 * @param string $packageKey The package key to fetch the suggestions for
732 * @return array|NULL An array of directly suggested packages
733 */
734 protected function getSuggestionArrayForPackage($packageKey)
735 {
736 if (!isset($this->packages[$packageKey])) {
737 return null;
738 }
739 $suggestedPackageKeys = array();
740 $suggestedPackageConstraints = $this->packages[$packageKey]->getPackageMetaData()->getConstraintsByType(MetaData::CONSTRAINT_TYPE_SUGGESTS);
741 foreach ($suggestedPackageConstraints as $constraint) {
742 if ($constraint instanceof MetaData\PackageConstraint) {
743 $suggestedPackageKey = $constraint->getValue();
744 if (isset($this->packages[$suggestedPackageKey])) {
745 $suggestedPackageKeys[] = $suggestedPackageKey;
746 }
747 }
748 }
749 return array_reverse($suggestedPackageKeys);
750 }
751
752 /**
753 * Saves the current content of $this->packageStatesConfiguration to the
754 * PackageStates.php file.
755 *
756 * @throws Exception\PackageStatesFileNotWritableException
757 */
758 protected function sortAndSavePackageStates()
759 {
760 $this->sortAvailablePackagesByDependencies();
761
762 $this->packageStatesConfiguration['version'] = 4;
763
764 $fileDescription = "# PackageStates.php\n\n";
765 $fileDescription .= "# This file is maintained by TYPO3's package management. Although you can edit it\n";
766 $fileDescription .= "# manually, you should rather use the extension manager for maintaining packages.\n";
767 $fileDescription .= "# This file will be regenerated automatically if it doesn't exist. Deleting this file\n";
768 $fileDescription .= "# should, however, never become necessary if you use the package commands.\n";
769
770 // We do not need the dependencies and suggestions on disk...
771 foreach ($this->packageStatesConfiguration['packages'] as &$packageConfiguration) {
772 if (isset($packageConfiguration['dependencies'])) {
773 unset($packageConfiguration['dependencies']);
774 }
775 if (isset($packageConfiguration['suggestions'])) {
776 unset($packageConfiguration['suggestions']);
777 }
778 }
779 if (!@is_writable($this->packageStatesPathAndFilename)) {
780 // If file does not exists try to create it
781 $fileHandle = @fopen($this->packageStatesPathAndFilename, 'x');
782 if (!$fileHandle) {
783 throw new Exception\PackageStatesFileNotWritableException(
784 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),
785 1382449759
786 );
787 }
788 fclose($fileHandle);
789 }
790 $packageStatesCode = "<?php\n$fileDescription\nreturn " . ArrayUtility::arrayExport($this->packageStatesConfiguration) . ";\n";
791 GeneralUtility::writeFile($this->packageStatesPathAndFilename, $packageStatesCode, true);
792
793 $this->initializeCompatibilityLoadedExtArray();
794
795 GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive($this->packageStatesPathAndFilename);
796 }
797
798 /**
799 * Check the conformance of the given package key
800 *
801 * @param string $packageKey The package key to validate
802 * @return bool If the package key is valid, returns TRUE otherwise FALSE
803 * @api
804 */
805 public function isPackageKeyValid($packageKey)
806 {
807 return preg_match(PackageInterface::PATTERN_MATCH_PACKAGEKEY, $packageKey) === 1 || preg_match(PackageInterface::PATTERN_MATCH_EXTENSIONKEY, $packageKey) === 1;
808 }
809
810 /**
811 * Returns an array of \TYPO3\CMS\Core\Package objects of all available packages.
812 * A package is available, if the package directory contains valid meta information.
813 *
814 * @return PackageInterface[] Array of PackageInterface
815 * @api
816 */
817 public function getAvailablePackages()
818 {
819 return $this->packages;
820 }
821
822 /**
823 * Unregisters a package from the list of available packages
824 *
825 * @param PackageInterface $package The package to be unregistered
826 * @return void
827 * @throws Exception\InvalidPackageStateException
828 */
829 public function unregisterPackage(PackageInterface $package)
830 {
831 $packageKey = $package->getPackageKey();
832 if (!$this->isPackageAvailable($packageKey)) {
833 throw new Exception\InvalidPackageStateException('Package "' . $packageKey . '" is not registered.', 1338996142);
834 }
835 $this->unregisterPackageByPackageKey($packageKey);
836 }
837
838 /**
839 * Reloads a package and its information
840 *
841 * @param string $packageKey
842 * @throws Exception\InvalidPackageStateException if the package isn't available
843 * @throws Exception\InvalidPackageKeyException if an invalid package key was passed
844 * @throws Exception\InvalidPackagePathException if an invalid package path was passed
845 * @throws Exception\InvalidPackageManifestException if no extension configuration file could be found
846 */
847 public function reloadPackageInformation($packageKey)
848 {
849 if (!$this->isPackageAvailable($packageKey)) {
850 throw new Exception\InvalidPackageStateException('Package "' . $packageKey . '" is not registered.', 1436201329);
851 }
852
853 /** @var PackageInterface $package */
854 $package = $this->packages[$packageKey];
855 $packagePath = $package->getPackagePath();
856 $newPackage = new Package($this, $packageKey, $packagePath);
857 $this->packages[$packageKey] = $newPackage;
858 unset($package);
859 }
860
861 /**
862 * Returns contents of Composer manifest as a stdObject
863 *
864 * @param string $manifestPath
865 * @return \stdClass
866 * @throws Exception\MissingPackageManifestException
867 * @throws Exception\InvalidPackageManifestException
868 */
869 public function getComposerManifest($manifestPath)
870 {
871 $composerManifest = null;
872 if (file_exists($manifestPath . 'composer.json')) {
873 $json = file_get_contents($manifestPath . 'composer.json');
874 $composerManifest = json_decode($json);
875 if (!$composerManifest instanceof \stdClass) {
876 throw new Exception\InvalidPackageManifestException('The composer.json found for extension "' . basename($manifestPath) . '" is invalid!', 1439555561);
877 }
878 }
879
880 try {
881 $extensionManagerConfiguration = $this->getExtensionEmConf($manifestPath);
882 $composerManifest = $this->mapExtensionManagerConfigurationToComposerManifest(
883 basename($manifestPath),
884 $extensionManagerConfiguration,
885 $composerManifest ?: new \stdClass()
886 );
887 } catch (Exception\InvalidPackageManifestException $e) {
888 if ($composerManifest === null) {
889 throw $e;
890 }
891 }
892
893 return $composerManifest;
894 }
895
896 /**
897 * Fetches MetaData information from ext_emconf.php, used for
898 * resolving dependencies as well.
899 *
900 * @param string $packagePath
901 * @return array
902 * @throws Exception\InvalidPackageManifestException
903 */
904 protected function getExtensionEmConf($packagePath)
905 {
906 $packageKey = basename($packagePath);
907 $_EXTKEY = $packageKey;
908 $path = $packagePath . 'ext_emconf.php';
909 $EM_CONF = null;
910 if (@file_exists($path)) {
911 include $path;
912 if (is_array($EM_CONF[$_EXTKEY])) {
913 return $EM_CONF[$_EXTKEY];
914 }
915 }
916 throw new Exception\InvalidPackageManifestException('No valid ext_emconf.php file found for package "' . $packageKey . '".', 1360403545);
917 }
918
919 /**
920 * Fetches information from ext_emconf.php and maps it so it is treated as it would come from composer.json
921 *
922 * @param string $packageKey
923 * @param array $extensionManagerConfiguration
924 * @param \stdClass $composerManifest
925 * @return \stdClass
926 * @throws Exception\InvalidPackageManifestException
927 */
928 protected function mapExtensionManagerConfigurationToComposerManifest($packageKey, array $extensionManagerConfiguration, \stdClass $composerManifest)
929 {
930 $this->setComposerManifestValueIfEmpty($composerManifest, 'name', $packageKey);
931 $this->setComposerManifestValueIfEmpty($composerManifest, 'type', 'typo3-cms-extension');
932 $this->setComposerManifestValueIfEmpty($composerManifest, 'description', $extensionManagerConfiguration['title']);
933 $composerManifest->version = $extensionManagerConfiguration['version'];
934 if (isset($extensionManagerConfiguration['constraints']['depends']) && is_array($extensionManagerConfiguration['constraints']['depends'])) {
935 $composerManifest->require = new \stdClass();
936 foreach ($extensionManagerConfiguration['constraints']['depends'] as $requiredPackageKey => $requiredPackageVersion) {
937 if (!empty($requiredPackageKey)) {
938 if ($requiredPackageKey === 'typo3') {
939 // Add implicit dependency to 'core'
940 $composerManifest->require->core = $requiredPackageVersion;
941 } elseif ($requiredPackageKey !== 'php') {
942 // Skip php dependency
943 $composerManifest->require->{$requiredPackageKey} = $requiredPackageVersion;
944 }
945 } else {
946 throw new Exception\InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in depends section. Extension key is missing!', $packageKey), 1439552058);
947 }
948 }
949 }
950 if (isset($extensionManagerConfiguration['constraints']['conflicts']) && is_array($extensionManagerConfiguration['constraints']['conflicts'])) {
951 $composerManifest->conflict = new \stdClass();
952 foreach ($extensionManagerConfiguration['constraints']['conflicts'] as $conflictingPackageKey => $conflictingPackageVersion) {
953 if (!empty($conflictingPackageKey)) {
954 $composerManifest->conflict->$conflictingPackageKey = $conflictingPackageVersion;
955 } else {
956 throw new Exception\InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in conflicts section. Extension key is missing!', $packageKey), 1439552059);
957 }
958 }
959 }
960 if (isset($extensionManagerConfiguration['constraints']['suggests']) && is_array($extensionManagerConfiguration['constraints']['suggests'])) {
961 $composerManifest->suggest = new \stdClass();
962 foreach ($extensionManagerConfiguration['constraints']['suggests'] as $suggestedPackageKey => $suggestedPackageVersion) {
963 if (!empty($suggestedPackageKey)) {
964 $composerManifest->suggest->$suggestedPackageKey = $suggestedPackageVersion;
965 } else {
966 throw new Exception\InvalidPackageManifestException(sprintf('The extension "%s" has invalid version constraints in suggests section. Extension key is missing!', $packageKey), 1439552060);
967 }
968 }
969 }
970 if (isset($extensionManagerConfiguration['autoload'])) {
971 $composerManifest->autoload = json_decode(json_encode($extensionManagerConfiguration['autoload']));
972 }
973 // composer.json autoload-dev information must be discarded, as it may contain information only available after a composer install
974 unset($composerManifest->{'autoload-dev'});
975 if (isset($extensionManagerConfiguration['autoload-dev'])) {
976 $composerManifest->{'autoload-dev'} = json_decode(json_encode($extensionManagerConfiguration['autoload-dev']));
977 }
978
979 return $composerManifest;
980 }
981
982 /**
983 * @param \stdClass $manifest
984 * @param string $property
985 * @param mixed $value
986 * @return \stdClass
987 */
988 protected function setComposerManifestValueIfEmpty(\stdClass $manifest, $property, $value)
989 {
990 if (empty($manifest->{$property})) {
991 $manifest->{$property} = $value;
992 }
993
994 return $manifest;
995 }
996
997 /**
998 * Returns an array of dependent package keys for the given package. It will
999 * do this recursively, so dependencies of dependant packages will also be
1000 * in the result.
1001 *
1002 * @param string $packageKey The package key to fetch the dependencies for
1003 * @param array $dependentPackageKeys
1004 * @param array $trace An array of already visited package keys, to detect circular dependencies
1005 * @return array|NULL An array of direct or indirect dependant packages
1006 * @throws Exception\InvalidPackageKeyException
1007 */
1008 protected function getDependencyArrayForPackage($packageKey, array &$dependentPackageKeys = array(), array $trace = array())
1009 {
1010 if (!isset($this->packages[$packageKey])) {
1011 return null;
1012 }
1013 if (in_array($packageKey, $trace, true) !== false) {
1014 return $dependentPackageKeys;
1015 }
1016 $trace[] = $packageKey;
1017 $dependentPackageConstraints = $this->packages[$packageKey]->getPackageMetaData()->getConstraintsByType(MetaData::CONSTRAINT_TYPE_DEPENDS);
1018 foreach ($dependentPackageConstraints as $constraint) {
1019 if ($constraint instanceof MetaData\PackageConstraint) {
1020 $dependentPackageKey = $constraint->getValue();
1021 if (in_array($dependentPackageKey, $dependentPackageKeys, true) === false && in_array($dependentPackageKey, $trace, true) === false) {
1022 $dependentPackageKeys[] = $dependentPackageKey;
1023 }
1024 $this->getDependencyArrayForPackage($dependentPackageKey, $dependentPackageKeys, $trace);
1025 }
1026 }
1027 return array_reverse($dependentPackageKeys);
1028 }
1029
1030 /**
1031 * Resolves package key from Composer manifest
1032 *
1033 * If it is a TYPO3 package the name of the containing directory will be used.
1034 *
1035 * Else if the composer name of the package matches the first part of the lowercased namespace of the package, the mixed
1036 * case version of the composer name / namespace will be used, with backslashes replaced by dots.
1037 *
1038 * Else the composer name will be used with the slash replaced by a dot
1039 *
1040 * @param object $manifest
1041 * @param string $packagePath
1042 * @param string $packagesBasePath
1043 * @throws Exception\InvalidPackageManifestException
1044 * @return string
1045 */
1046 protected function getPackageKeyFromManifest($manifest, $packagePath, $packagesBasePath)
1047 {
1048 if (!is_object($manifest)) {
1049 throw new Exception\InvalidPackageManifestException('Invalid composer manifest in package path: ' . $packagePath, 1348146451);
1050 }
1051 if (isset($manifest->type) && substr($manifest->type, 0, 10) === 'typo3-cms-') {
1052 $relativePackagePath = substr($packagePath, strlen($packagesBasePath));
1053 $packageKey = substr($relativePackagePath, strpos($relativePackagePath, '/') + 1, -1);
1054 return preg_replace('/[^A-Za-z0-9._-]/', '', $packageKey);
1055 } else {
1056 $packageKey = str_replace('/', '.', $manifest->name);
1057 return preg_replace('/[^A-Za-z0-9.]/', '', $packageKey);
1058 }
1059 }
1060 }